package kr.co.compcareworker.Fragment.Machine;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
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.DividerItemDecoration;
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.util.HashMap;

import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.Company.Machine.AlarmData;
import kr.co.compcareworker.MyApplication;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.AlarmListAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Firebase.MyFirebaseMessagingService;

public class Alarm_List_Fragment extends Fragment {

    private FragmentActivity fa;
    private Handler hdr;
    private ImageView alarm_list_removeIV, searchIV;
    private RecyclerView alarm_listRV;
    private ProgressBar alarm_listPB;
    private ArrayItem<AlarmData> items;
    private AlarmListAdapter adapter;
    private int lastIndex = 0, limitCount = 50, count = 0;
    private TextView not_checked_alarm_countTV;
    private EditText search_cp_nameET;
    private LinearLayout alarm_all_checkLL;
    private final String[] arr_str = new String[]{"미처리", "처리", "전체"};
    private final String[] sort_type = new String[]{"A", "B", "C"};
    private int sort_position = 0;

    @SuppressLint("ValidFragment")
    public Alarm_List_Fragment(Handler handler) {
        this.hdr = handler;
    }

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

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

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.frag_alarm_list, container, false);

        alarm_list_removeIV = v.findViewById(R.id.alarm_list_removeIV);
        alarm_listRV = v.findViewById(R.id.alarm_listRV);
        alarm_listPB = v.findViewById(R.id.alarm_listPB);
        not_checked_alarm_countTV = v.findViewById(R.id.not_checked_alarm_countTV);
        search_cp_nameET = v.findViewById(R.id.search_cp_nameET);
        searchIV = v.findViewById(R.id.searchIV);
        alarm_all_checkLL = v.findViewById(R.id.alarm_all_checkLL);

        adapter = new AlarmListAdapter(getContext(), hdr, new AlarmListAdapter.completeListener() {
            @Override
            public void onClick(String mcl_idx) {

                alarm_listPB.setVisibility(View.VISIBLE);
                HashMap<String, String> data = new HashMap<>();
                data.put("mcl_idx", mcl_idx);
                data.put("mb_name", fa.userItem.getArrayitem().getMbName());
                new ApiClient(data, "proc_alarm_check", hdr);
            }

            @Override
            public void onMemoSave(String mcl_idx, String memo) {
                alarm_listPB.setVisibility(View.VISIBLE);
                HashMap<String, String> data = new HashMap<>();
                data.put("mcl_idx", mcl_idx);
                data.put("engineer_check_memo", memo);
                new ApiClient(data, "proc_alarm_check_memo", hdr);
            }

            @Override
            public void onInvoice(String cp_idx) {
                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "거래내역");
                intent.putExtra("type", "invoice_list");
                intent.putExtra("value1", cp_idx);
                startActivity(intent);
            }
        }, new AlarmListAdapter.OnLoadMoreListener() {
            @Override
            public void onLoadMore(int position) {
                if (count == limitCount) {
                    lastIndex += limitCount;
                    Get_Contents();
                }
            }
        });
        alarm_listRV.setAdapter(adapter);
        alarm_listRV.setHasFixedSize(true);
        alarm_listRV.addItemDecoration(new DividerItemDecoration(getContext(), 1));

        init_Handler();
        Get_Contents();
        init_Listener();

        return v;
    }

    void Get_Contents() {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                alarm_listPB.setVisibility(View.VISIBLE);
            }
        }, 0);
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        if (!TextUtils.isEmpty(search_cp_nameET.getText())) data.put("search", search_cp_nameET.getText().toString());
        data.put("per_page", limitCount + "");
        data.put("offset", lastIndex + "");
        data.put("type", sort_type[sort_position]);
        new ApiClient(data, "proc_get_alarm_list2", hdr);
    }

    void init_Listener() {

        alarm_list_removeIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alarm_listPB.setVisibility(View.VISIBLE);
                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                new ApiClient(data, "proc_alarm_engineer_read", hdr);
            }
        });

        search_cp_nameET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() == 0 || charSequence.length() > 1) {
                    Get_Contents();
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        search_cp_nameET.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_ENTER) {
                    Get_Contents();
                    return true;
                }
                return false;
            }
        });

        searchIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Get_Contents();
            }
        });

        alarm_all_checkLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alarm_listPB.setVisibility(View.VISIBLE);
                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                data.put("mb_name", fa.userItem.getArrayitem().getMbName());
                new ApiClient(data, "proc_alarm_check", hdr);
            }

        });

        not_checked_alarm_countTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                alertDialogBuilder.setSingleChoiceItems(arr_str, sort_position, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, final int which) {
                        sort_position = which;
                        lastIndex = 0;
                        count = 0;
                        Get_Contents();
                        dialog.dismiss();
                    }
                });
                alertDialogBuilder.show();
            }
        });
    }

    public void refresh() {
        Get_Contents();
    }

    @Override
    public void onResume() {
        super.onResume();
        MyFirebaseMessagingService.alarmListFragment = this;
        Get_Contents();
    }

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

                String url = msg.getData().getString("url");

                if (msg.what == 1) {

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

                        if (items.isSuccess()) {
                            String not_read_cnt = result_item.get("resultItem").getAsJsonObject().get("message").getAsString();
                            not_read_cnt = not_read_cnt.substring(0, not_read_cnt.indexOf("+"));
                            int cnt = Integer.parseInt(not_read_cnt);

                            String not_checked_cnt = result_item.get("resultItem").getAsJsonObject().get("message").getAsString();
                            not_checked_cnt = not_checked_cnt.substring(not_checked_cnt.indexOf("+") + 1);

                            if (sort_position < 2) {
                                not_checked_alarm_countTV.setText(arr_str[sort_position] + " (" + not_checked_cnt + "건) ▼");
                            } else {
                                not_checked_alarm_countTV.setText(arr_str[sort_position] +" ▼");
                            }

                            if (cnt == 0) {
                                if (MyApplication.alarm_thread != null) {
                                    MyApplication.alarm_thread.stopForever();
                                    MyApplication.alarm_thread = null;
                                }

                                if (MyApplication.notify_manager != null) {
                                    MyApplication.notify_manager.cancelAll();
                                }
                            }
                            count = items.size();

                            if (lastIndex != 0) {
                                adapter.addItemMore(items.getArrayitem());
                            } else {
                                adapter.addAll(items.getArrayitem());
                            }

                        } else {
                            adapter.clearItem();
                            not_checked_alarm_countTV.setText(arr_str[sort_position] + " (0건) ▼");
                            String search = search_cp_nameET.getText().toString();
                            if (TextUtils.isEmpty(search)) Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    } else if (url.equals("proc_alarm_check")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Get_Contents();

                        } else {
                            Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    } else if (url.equals("proc_alarm_engineer_read")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Get_Contents();

                        } else {
                            Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    } else if (url.equals("proc_alarm_check_memo")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Get_Contents();

                        } else {
                            Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                } else if (msg.what == -1) {
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                }
                alarm_listPB.setVisibility(View.GONE);
            }
        };
    }
}

