package kr.co.compcarecompany.Fragment.Main;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ComponentName;
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.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
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 androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

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

import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Activity.WebviewAct;
import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.Company.CompanyData;
import kr.co.compcarecompany.MyApplication;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.MenuAlarmAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.MyOnItemClick;

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

    FragmentActivity fa;
    String type;

    TextView menu1, menu2, menu3, menu4, menu5, menu6, menu7, updateTV;
    LinearLayout notiFrame, alarm_notifyLL, versionLL;
    Switch noti, alarm_notifySW;
    RecyclerView alarm_notifyRV;
    CompanyData companyData;
    MenuAlarmAdapter adapter;
    ArrayItem<CompanyData> items = new ArrayItem<>();

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

    @Override
    public void onDetach() {
        super.onDetach();
        fa = null;
        Log.d("메뉴@@@@", "종료!!!!");
    }

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

    public Main_Menu_Fragment(Handler handler, String type, CompanyData companyData) {
        this.handler = handler;
        this.type = type;
        this.companyData = companyData;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_main_menu, 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);
        menu6 = v.findViewById(R.id.menu6);
        menu7 = v.findViewById(R.id.menu7);

        notiFrame = v.findViewById(R.id.notiFrame);
        noti = v.findViewById(R.id.noti);

        versionLL = v.findViewById(R.id.versionLL);
        updateTV = v.findViewById(R.id.updateTV);

        alarm_notifyLL = v.findViewById(R.id.alarm_notifyLL);
        alarm_notifySW = v.findViewById(R.id.alarm_notifySW);
        alarm_notifyRV = v.findViewById(R.id.alarm_notifyRV);

        Intent intent = getActivity().getIntent();
        companyData = (CompanyData) intent.getSerializableExtra("value2");

        init_Handler();
        init_Listener();

        Get_version();
        Set_Contents();

        return v;
    }

    void Set_Contents() {

        if (Common.getInstance().getPref(getContext(), "noti_x", false)) {
            noti.setChecked(false);
        } else {
            noti.setChecked(true);
        }

        if (Common.getInstance().getPref(getContext(), "alarm_noti_x", true)) {
            alarm_notifySW.setChecked(false);
        } else {
            alarm_notifySW.setChecked(true);
            Get_Partner();
        }
    }

    void Set_AlarmList() {

        adapter = new MenuAlarmAdapter(getContext(), this::onClick);
        alarm_notifyRV.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        alarm_notifyRV.setAdapter(adapter);
        adapter.addItem(items.getArrayitem());
    }

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

    void Get_Partner() {

        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", companyData.getAgIdx());
        data.put("pt_idx", companyData.getPtIdx());
        data.put("type", "COMPANY");
        new ApiClient(data, "proc_admin_partner_view", handler);
    }

    void init_Handler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                String url = msg.getData().getString("url");
                if (url.equals("proc_admin_partner_view")) {
                    JsonElement element = new JsonParser().parse(msg.obj.toString());
                    JsonObject result_item = element.getAsJsonObject();
                    items = new Gson().fromJson(result_item, new TypeToken<ArrayItem<CompanyData>>() {
                    }.getType());

                    if (items.isSuccess()) {
                        Set_AlarmList();
                    } else {
                        Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_LONG).show();
                        getActivity().finish();
                    }
                } else if (url.equals("proc_remove_token")) {
                    JsonElement element = new JsonParser().parse(msg.obj.toString());
                    JsonObject result_item = element.getAsJsonObject();

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

                        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);
                    }

                    Common.getInstance().toastShow(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString());
                } else 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)) {
                            menu5.setText("버전정보 ( 최신버전 "+market_version+" 사용중 )");
                            updateTV.setVisibility(View.GONE);
                        } else {
                            menu5.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) {

                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "프로필 수정");
                intent.putExtra("type", "member_info");
                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) {

                        //21.10.12 로그아웃 시 해당기기에 알람이 안 오도록 설정함.
                        if (MyApplication.alarm_thread != null) {
                            MyApplication.alarm_thread.stopForever();
                            MyApplication.alarm_thread = null;
                        }

                        if (MyApplication.notify_manager != null)
                            MyApplication.notify_manager.cancelAll();

                        HashMap<String, String> data = new HashMap<>();
                        data.put("mb_idx", fa.userItem.getArrayitem().getMbIdx());
                        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                        new ApiClient(data, "proc_remove_token", handler);
                        ////

                        dialog.dismiss();

                    }
                }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.show();
            }
        });

        menu3.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);
            }
        });

        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/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);
            }
        });

        menu6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "멤버 관리");
                intent.putExtra("type", "member_management");
                startActivity(intent);
            }
        });

        menu7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "도움말");
                intent.putExtra("type", "help_service");
                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);

                    //21.10.12 알람을 비활성화 하면 현재 울리고 있는 알람도 종료해준다.
                    if (MyApplication.alarm_thread != null && MyApplication.alarm_thread.get_alarmThread_title().contains("서비스 접수")) {
                        MyApplication.alarm_thread.stopForever();
                        MyApplication.alarm_thread = null;

                        if (MyApplication.notify_manager != null)
                            MyApplication.notify_manager.cancelAll();
                    }
                    ////
                }
            }
        });

        alarm_notifySW.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Common.getInstance().delPref(getContext(), "alarm_noti_x");
                    Get_Partner();
                    alarm_notifyRV.setVisibility(View.VISIBLE);

                } else {
                    Common.getInstance().setPref(getContext(), "alarm_noti_x", true);

                    //21.10.12 알람을 비활성화 하면 현재 울리고 있는 알람도 종료해준다.
                    if (MyApplication.alarm_thread != null && !MyApplication.alarm_thread.get_alarmThread_title().contains("서비스 접수")) {
                        MyApplication.alarm_thread.stopForever();
                        MyApplication.alarm_thread = null;

                        if (MyApplication.notify_manager != null)
                            MyApplication.notify_manager.cancelAll();
                    }
                    ////
                    alarm_notifyRV.setVisibility(View.GONE);
                }
            }
        });
    }

    //주의 경고음 상태 프리퍼런스에 저장함
    @Override
    public void onClick(Bundle value) {

        if (value.getBoolean("state")) {
            Common.getInstance().setPref(getContext(), value.getString("cp_idx"), value.getBoolean("state"));

        } else {
            Common.getInstance().delPref(getContext(), value.getString("cp_idx"));

            //21.10.12 알람을 비활성화 하면 현재 울리고 있는 알람도 종료해준다.
            if (MyApplication.alarm_thread != null && !MyApplication.alarm_thread.get_alarmThread_title().contains("서비스 접수") && MyApplication.alarm_thread.get_alarmThread_cpIdx().equals(value.getString("cp_idx"))) {
                MyApplication.alarm_thread.stopForever();
                MyApplication.alarm_thread = null;

                if (MyApplication.notify_manager != null)
                    MyApplication.notify_manager.cancelAll();
            }
        }
        Common.getInstance().setPref(getContext(), "saved_alarm_setting", true);
    }
}
