package kr.co.compcarecompany.Fragment.Main;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
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.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.ArrayList;
import java.util.HashMap;

import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.ArrayItem_;
import kr.co.compcarecompany.Data.Product.MachineItem;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.OptionInterlockAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;

public class Option_Interlock_Fragment extends Fragment {

    private Handler handler;
    private FragmentActivity fa;

    private TextView interlock_cp_nameTV, interlock_airlineTV, interlock_selected_macTV, interlock_selected_pd_nameTV, cancelTV, saveTV, interlock_typeTV, option_machine_settingTV, option_alarm_settingTV, interlock_sub_typeTV;
    private EditText interlock_cross_timeET,  interlock_sub_pressET, interlock_delay_timeET, interlock_low_pressET, interlock_loadkill_timeET, interlock_unloadkill_timeET, interlock_call_slave;
    private String cp_idx, mc_idx, interlock_yn = "N",interlock_yn1 = "N", cp_airline, interlock_type = "M", mc_idx2, mac2,  mc_yeon_type;
    private RadioGroup interlockRG, interlockRG1 ;
    private RadioButton interlock_yRBtn, interlock_nRBtn, interlock_yRBtn1, interlock_nRBtn1;
    private ProgressBar interlockPB;
    private Context context;
    private ArrayItem_<MachineItem> machine_item;
    private ArrayList<String> Mc_index  = new ArrayList<String>();
    private ArrayList<String> Mac_total  = new ArrayList<String>();
    private ArrayList<String> Cross_num  = new ArrayList<String>();
    private ArrayList<String> index_total  = new ArrayList<String>();
    private RecyclerView interlock_listRV;
    private OptionInterlockAdapter adapter;

    @SuppressLint("ValidFragment")
    public Option_Interlock_Fragment(Handler handler, String cp_idx, String mc_idx, String cp_airline) {
        this.handler = handler;
        this.cp_idx = mc_idx;
        this.mc_idx = mc_idx;
        this.cp_airline = cp_airline;
    }

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

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

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

        interlock_cp_nameTV = v.findViewById(R.id.interlock_cp_nameTV);
        interlock_airlineTV = v.findViewById(R.id.interlock_airlineTV);
        interlock_selected_macTV = v.findViewById(R.id.interlock_selected_macTV);
        interlock_selected_pd_nameTV = v.findViewById(R.id.interlock_selected_pd_nameTV);
        interlockRG = v.findViewById(R.id.interlockRG);
        interlockRG1 = v.findViewById(R.id.interlockRG1);
        interlock_cross_timeET = v.findViewById(R.id.interlock_cross_timeET);

        interlock_low_pressET = v.findViewById(R.id.interlock_low_pressET);
        interlock_sub_pressET = v.findViewById(R.id.interlock_sub_pressET);
        interlock_delay_timeET = v.findViewById(R.id.interlock_delay_timeET);
        interlock_loadkill_timeET = v.findViewById(R.id.interlock_loadkill_timeET);
        interlock_unloadkill_timeET = v.findViewById(R.id.interlock_unloadkill_timeET);
        interlock_call_slave = v.findViewById(R.id.interlock_call_slave);
        cancelTV = v.findViewById(R.id.cancelTV);
        saveTV = v.findViewById(R.id.saveTV);
        interlock_typeTV = v.findViewById(R.id.interlock_typeTV);
        interlockPB = v.findViewById(R.id.interlockPB);
        option_machine_settingTV = v.findViewById(R.id.option_machine_settingTV);
        option_alarm_settingTV = v.findViewById(R.id.option_alarm_settingTV);
        interlock_listRV = v.findViewById(R.id.interlock_listRV);
        interlock_sub_typeTV = v.findViewById(R.id.interlock_sub_typeTV);
        interlock_yRBtn = v.findViewById(R.id.interlock_yRBtn);
        interlock_nRBtn = v.findViewById(R.id.interlock_nRBtn);
        interlock_yRBtn1 = v.findViewById(R.id.interlock_yRBtn1);
        interlock_nRBtn1 = v.findViewById(R.id.interlock_nRBtn1);

        context = getActivity().getBaseContext();
        adapter = new OptionInterlockAdapter(context, clickListener);

        init_Handler();
        Get_Machine_List();
        init_Listener();

        return v;
    }

    void Get_Machine_List() {
        HashMap<String, String> data = new HashMap<>();
        data.put("mc_idx", mc_idx);
        new ApiClient(data, "proc_get_interlock_machine", handler);
    }

    void Set_Content() {

        interlock_cp_nameTV.setText(Common.getInstance().isNull(machine_item.getArrayitem().getCpName()).toString());
        interlock_airlineTV.setText("[ " + Common.getInstance().isNull(machine_item.getArrayitem().getMcAirline())+" ]");
        interlock_selected_macTV.setText("MAC ("+Common.getInstance().isNull(machine_item.getArrayitem().getMcIotMac())+")");
        interlock_selected_pd_nameTV.setText(Common.getInstance().isNull(machine_item.getArrayitem().getPdName()).toString());

        if (machine_item.getArrayitem().getMcYeonYn() != null && machine_item.getArrayitem().getMcYeonYn().equals("N")) {
            interlockRG.check(R.id.interlock_yRBtn);
            interlockRG1.check(R.id.interlock_yRBtn1);
        } else {
            interlockRG.check(R.id.interlock_nRBtn);
            interlockRG1.check(R.id.interlock_nRBtn1);
        }


        // 23.08.21 선택한 기계 항상 마스터, 이하 슬래이브 고정
        interlock_type = "M";
        interlock_sub_typeTV.setText("SLAVE");
        interlock_cross_timeET.setText(Common.getInstance().isNullToZero(machine_item.getArrayitem().getMcYeonCrossTime())+"");
        interlock_sub_pressET.setText(Common.getInstance().isNullToZeroFloat(machine_item.getArrayitem().getMcYeonSubPress())+"");
        interlock_delay_timeET.setText(Common.getInstance().isNullToZero(machine_item.getArrayitem().getMcYeonSubTime())+"");
        interlock_unloadkill_timeET.setText(Common.getInstance().isNullToZero(machine_item.getArrayitem().getMcUnloadKillSec())+"");
        interlock_loadkill_timeET.setText(Common.getInstance().isNullToZero(machine_item.getArrayitem().getMcLoadKillSec())+"");
        interlock_low_pressET.setText(Common.getInstance().isNullToZero(machine_item.getArrayitem().getMcYeonLowPress())+"");
        interlock_call_slave.setText(Common.getInstance().isNullToZero(machine_item.getArrayitem().getMcCallSlave())+"");
    }

    void init_Listener() {

        //기기설정 클릭 리스너
        option_machine_settingTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (interlockPB.getVisibility() == View.VISIBLE) {
                    Common.getInstance().toastShow(context, "데이터를 가져오는 중입니다.\n잠시후 다시 시도해주세요.");
                    return;
                }

                Intent intent = new Intent(context, FragmentActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                intent.putExtra("title", "기계 옵션설정");
                intent.putExtra("type", "option_machine");
                intent.putExtra("value1", mc_idx);
                intent.putExtra("value2", cp_airline);
                fa.finish();
                startActivity(intent);
            }
        });

        //IoT 기동설정 클릭 리스너
        option_alarm_settingTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (interlockPB.getVisibility() == View.VISIBLE) {
                    Common.getInstance().toastShow(context, "데이터를 가져오는 중입니다.\n잠시후 다시 시도해주세요.");
                    return;
                }

                Intent intent = new Intent(context, FragmentActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                intent.putExtra("title", "기계 옵션설정");
                intent.putExtra("type", "option_iot");
                intent.putExtra("value1", machine_item.getArrayitem().getMcIdx());
                intent.putExtra("value2", machine_item.getArrayitem().getCpIdx());
                intent.putExtra("value3", machine_item.getArrayitem().getMcIotMac());
                intent.putExtra("value4", cp_airline);
                fa.finish();
                startActivity(intent);

            }
        });

        //연동제어 사용여부
        interlockRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {
                    case R.id.interlock_yRBtn:
                        interlock_yn = "Y";
                        break;
                    case R.id.interlock_nRBtn:
                        interlock_yn = "N";
                        break;
                }
            }
        });

        //교번제어 사용여부
        interlockRG1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {
                    case R.id.interlock_yRBtn1:
                        interlock_yn1 = "Y";
                        interlock_cross_timeET.setText("1");
                        interlock_cross_timeET.setEnabled(true);

                        break;
                    case R.id.interlock_nRBtn1:
                        interlock_yn1 = "N";
                        interlock_cross_timeET.setText("999999");
                        interlock_cross_timeET.setEnabled(false);
                        break;
                }
            }
        });

        //연동제어 닫기버튼 클릭 리스너
        cancelTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fa.finish();
            }
        });

        //연동제어 저장버튼 클릭 리스너
        saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // saveTV.setEnabled(false);
                // interlockPB.setVisibility(View.VISIBLE);
                save_setting();
            }
        });
    }
  
    // 23.08.21 연동제어 시작점
    void save_setting() {
        /*
        if (TextUtils.isEmpty(mc_idx2)) {
            Common.getInstance().toastShow(context, "연동할 기계를 선택하세요.");
            saveTV.setEnabled(true);
            interlockPB.setVisibility(View.GONE);
            return;
        }
        */

        Mc_index.add(machine_item.getArrayitem().getMcIdx()); // 마스터 MC_IDX
        Mac_total.add(machine_item.getArrayitem().getMcIotMac()); // 마스터 MC_IOT_MAC
        index_total.add("/"+machine_item.getArrayitem().getMcIotMac()+":"+0); // 마스터 정보
        Cross_num.add(String.valueOf(0)); // 마스터 INDEX 번호

            for (int i = 0; i < Mac_total.size(); i++) {


                if (Mac_total.get(i) == machine_item.getArrayitem().getMcIotMac()) {
                    mc_yeon_type = "M";
                } else {
                    mc_yeon_type = "S";
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("mac", Mac_total.get(i));
                data.put("mc_idx", Mc_index.get(i));
                data.put("mc_cross_num", Cross_num.get(i));
                data.put("mc_yeon_type", mc_yeon_type);
                data.put("mc_yeon_cross_time", Common.getInstance().isNullToZero(interlock_cross_timeET.getText().toString()));
                data.put("mc_yeon_low_press", Common.getInstance().isNullToZeroFloat(interlock_low_pressET.getText().toString()));
                data.put("mc_yeon_min_press", Common.getInstance().isNullToZeroFloat(interlock_sub_pressET.getText().toString()));
                data.put("mc_yeon_delay_sec", Common.getInstance().isNullToZero(interlock_delay_timeET.getText().toString()));
                data.put("mc_load_kill_sec", Common.getInstance().isNullToZero(interlock_loadkill_timeET.getText().toString()));
                data.put("mc_unload_kill_sec", Common.getInstance().isNullToZero(interlock_unloadkill_timeET.getText().toString()));
                data.put("mc_call_slave", Common.getInstance().isNullToZero(interlock_call_slave.getText().toString()));
                data.put("slave", index_total.toString().trim());
                data.put("mc_yeon_yn", interlock_yn);
                data.put("mc_cross_yn", interlock_yn1);

                new ApiClient(data, "kyoung", handler);

                // 1초씩 루틴 딜레이
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


        Mc_index.remove(machine_item.getArrayitem().getMcIdx());
        Mac_total.remove(machine_item.getArrayitem().getMcIotMac());
        index_total.remove("/"+machine_item.getArrayitem().getMcIotMac()+":"+0);
        Cross_num.remove(String.valueOf(0));

        Common.getInstance().toastShow(context, "연동제어 저장되었습니다.");

    }

    OptionInterlockAdapter.checkClickListener clickListener = new OptionInterlockAdapter.checkClickListener() {
        @Override
        public void clickBtn(int position, String mc_idx, String mac, Editable text) {

            interlock_nRBtn.setEnabled(true);
            interlock_yRBtn.setEnabled(true);
            interlock_nRBtn1.setEnabled(true);
            interlock_yRBtn1.setEnabled(true);

            Mc_index.add(mc_idx);
            Mac_total.add(mac);
            index_total.add("/"+mac +":"+ text);
            Cross_num.add(String.valueOf(text));

            for (int i=0; i<machine_item.getArrayitem().getInterlockList().size(); i++) {
                machine_item.getArrayitem().getInterlockList().get(i).setSelected(i == position);

                // 체크 박스 선택한 부분 값 넘기기.
            }
            adapter.addItem(machine_item.getArrayitem().getInterlockList());
        }

        @Override
        public void clickCancelBtn(int position, String mc_idx,  String mac, Editable text) {
            if(TextUtils.isEmpty(text)){
                Toast.makeText(context, "순번값이 없으면 연동제어는 불가합니다.", Toast.LENGTH_SHORT).show();
            }

           Mc_index.remove(mc_idx);
           Mac_total.remove(mac);
           index_total.remove("/"+mac +":"+ text);
           Cross_num.remove(String.valueOf(text));

           interlockRG.check(R.id.interlock_nRBtn);
           interlock_nRBtn.setEnabled(false);
           interlock_yRBtn.setEnabled(false);
            interlock_nRBtn1.setEnabled(false);
            interlock_yRBtn1.setEnabled(false);
        }

    };

    void init_Handler() {
        handler = 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_interlock_machine")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        machine_item = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<MachineItem>>() {
                        }.getType());

                        interlock_nRBtn.setEnabled(false);
                        interlock_yRBtn.setEnabled(false);
                        interlock_nRBtn1.setEnabled(false);
                        interlock_yRBtn1.setEnabled(false);

                        if (machine_item.isSuccess()) {
                            Set_Content();
                            interlock_listRV.setAdapter(adapter);
                            interlock_listRV.setHasFixedSize(true);

                            if (machine_item.getArrayitem().getInterlockList() != null) {

                                if (machine_item.getArrayitem().getMcYeonYn().equals("Y") && machine_item.getArrayitem().getMcYeonGroup() != null) {

                                    for (int i =0; i<machine_item.getArrayitem().getInterlockList().size(); i++) {

                                        if (machine_item.getArrayitem().getInterlockList().get(i).getMcIdx().equals(machine_item.getArrayitem().getMcYeonGroup())
                                                && machine_item.getArrayitem().getInterlockList().get(i).getMcYeonGroup().equals(machine_item.getArrayitem().getMcIdx())) {
                                            machine_item.getArrayitem().getInterlockList().get(i).setSelected(true);
                                            mc_idx2 = machine_item.getArrayitem().getInterlockList().get(i).getMcIdx();
                                            mac2 = machine_item.getArrayitem().getInterlockList().get(i).getMcIotMac();
                                            interlock_nRBtn.setEnabled(true);
                                            interlock_yRBtn.setEnabled(true);
                                            interlock_nRBtn1.setEnabled(true);
                                            interlock_yRBtn1.setEnabled(true);
                                            break;
                                        }
                                    }
                                }

                                adapter.addItem(machine_item.getArrayitem().getInterlockList());

                            } else {
                                Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                                fa.finish();
                            }

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                        }

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

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Toast.makeText(context, "연동제어 설정을 완료했습니다.", Toast.LENGTH_SHORT).show();
                            getActivity().finish();

                        } else {
                            Toast.makeText(getContext(), "연동제어 설정을 실패했습니다.", Toast.LENGTH_SHORT).show();
                        }
                        saveTV.setEnabled(true);
                    }

                } else {
                    Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                }
                interlockPB.setVisibility(View.GONE);
            }
        };
    }
}


