package kr.co.compcareworker.Fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.net.URLEncoder;
import java.util.HashMap;

import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Activity.WebviewAct;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;

@SuppressLint("ValidFragment")
public class Main_Menu_Fragment extends Fragment {
    private Handler handler, hdr;

    FragmentActivity fa;
    String type;

    TextView menu1, menu2, menu3, menu4, menu5, updateTV;
    Switch noti, alarm_noti;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        fa = (FragmentActivity) getActivity();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        fa = null;
    }

    @SuppressLint("ValidFragment")
    public Main_Menu_Fragment(Handler handler, String type) {
        this.handler = handler;
        this.type = type;
    }

    public Main_Menu_Fragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_setting, container, false);

        menu1 = v.findViewById(R.id.menu1);
        menu2 = v.findViewById(R.id.menu2);
        menu3 = v.findViewById(R.id.menu3);
        menu4 = v.findViewById(R.id.menu4);
        menu5 = v.findViewById(R.id.menu5);
        updateTV = v.findViewById(R.id.updateTV);
        noti = v.findViewById(R.id.noti);
        alarm_noti = v.findViewById(R.id.alarm_noti);

        init_Handler();
        init_Listener();

        if(type.equals("1")) {
            Get_version();
        } else {
            Set_Contents();
        }

        return v;
    }

    void Get_version(){
        HashMap<String, String> data = new HashMap<>();
        data.put("app_name", "WORKER");
        new ApiClient(data, "proc_get_app_version", handler);
    }

    void Set_Contents() {
        noti.setChecked(!Common.getInstance().getPref(getContext(), "noti_x", false));
        alarm_noti.setChecked(Common.getInstance().getPref(getContext(), "alarm_noti", true));
    }

    void init_Handler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == -1) {
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();

                } else if (msg.what == 1) {
                    String url = msg.getData().getString("url");

                    if (url.equals("proc_get_app_version")){
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {

                            String market_version = result_item.get("resultItem").getAsJsonObject().get("message").toString().replace("\"", "");
                            String app_version = getAppVersion();

                            if(market_version.equals(app_version)) {
                                menu3.setText("버전정보 ( 최신버전 "+market_version+" 사용중 )");
                                updateTV.setVisibility(View.GONE);
                            } else {
                                menu3.setText("버전정보 ( 구버전"+app_version+" 사용중 )");
                                updateTV.setVisibility(View.VISIBLE);
                            }
                            Set_Contents();
                        } else {
                            Common.getInstance().toastShow(getContext(), "앱 버전 체크에 실패했습니다. 잠시 후 다시 시도해주세요.");
                            getActivity().finish();
                        }
                    }
                }
            }
        };
    }

    private String getAppVersion() {
        PackageManager pm = getContext().getPackageManager();
        PackageInfo pInfo = null;

        try {
            pInfo = pm.getPackageInfo(getContext().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e1) {
            e1.printStackTrace();
        }

        String currentVersion = pInfo.versionName;

        return currentVersion;
    }

    private void init_Listener() {
        menu1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String incodeUrl = URLEncoder.encode("https://" + fa.userItem.getArrayitem().getAgency().getMbId() + ".compcare.co.kr/setting/" + fa.userItem.getArrayitem().getMbId() + "/write/" + fa.userItem.getArrayitem().getMbIdx());
                Intent intent = new Intent(getContext(), WebviewAct.class);
                intent.putExtra("title", "내 정보");
                intent.putExtra("url", "https://" + fa.userItem.getArrayitem().getAgency().getMbId() + ".compcare.co.kr/api/web/" + fa.userItem.getArrayitem().getMbId() + "/?url=" + incodeUrl);
                startActivity(intent);
            }
        });

        menu2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                dialogBuilder.setTitle("콤프케어 작업자");
                dialogBuilder.setMessage("로그아웃 하시겠습니까?");
                dialogBuilder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Common.getInstance().delPref(getContext(), "id");
                        Common.getInstance().delPref(getContext(), "pw");

                        Intent i = getActivity().getBaseContext().getPackageManager().
                                getLaunchIntentForPackage(getActivity().getBaseContext().getPackageName());
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(i);
                    }
                }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.show();
            }
        });

        menu4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String incodeUrl = URLEncoder.encode("https://" + fa.userItem.getArrayitem().getAgency().getMbId() + ".compcare.co.kr/board/lists/faq");
                Intent intent = new Intent(getContext(), WebviewAct.class);
                intent.putExtra("title", "1:1 문의");
                intent.putExtra("url", "https://" + fa.userItem.getArrayitem().getAgency().getMbId() + ".compcare.co.kr/api/web/" + fa.userItem.getArrayitem().getMbId() + "/?url=" + incodeUrl);
                startActivity(intent);
            }
        });

        menu5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String incodeUrl = URLEncoder.encode("https://" + fa.userItem.getArrayitem().getAgency().getMbId() + ".compcare.co.kr/board/lists/notice");
                Intent intent = new Intent(getContext(), WebviewAct.class);
                intent.putExtra("title", "공지사항");
                intent.putExtra("url", "https://" + fa.userItem.getArrayitem().getAgency().getMbId() + ".compcare.co.kr/api/web/" + fa.userItem.getArrayitem().getMbId() + "/?url=" + incodeUrl);
                startActivity(intent);
            }
        });

        updateTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(getContext())
                        .setMessage("최신버전이 있습니다.\n업데이트를 하시겠습니까?")
                        .setPositiveButton("업데이트", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                getActivity().finish();
                                Uri uri = Uri.parse("https://play.google.com/store/apps/details?id=" + getContext().getPackageName());
                                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                                startActivity(it);
                            }
                        })
                        .setNegativeButton("닫기", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        })
                        .setCancelable(false)
                        .show();
            }
        });

        noti.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Common.getInstance().delPref(getContext(), "noti_x");
                } else {
                    Common.getInstance().setPref(getContext(), "noti_x", true);
                }
            }
        });

        alarm_noti.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Common.getInstance().setPref(getContext(), "alarm_noti", true);
                } else {
                    Common.getInstance().delPref(getContext(), "alarm_noti");
                }
            }
        });
    }
}
