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.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
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 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 org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.HashMap;

import info.mqtt.android.service.MqttAndroidClient;
import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.Product.MonitoringData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.DecimalDigitsInputFilter;

public class Option_IoT_Fragment extends Fragment {

    private Handler handler;
    private FragmentActivity fa;

    private TextView option_saveTV, option_machine_settingTV, option_interlock_settingTV;
    private EditText option_ct1_upET, option_ct1_delayET, option_ct2_upET, option_ct3_upET, option_ntc_downET, option_ntc_2_downET,
            option_pt_downET, option_ntc_upET, option_ntc_2_upET, option_pt_upET, option_pr1_upET, option_pr2_upET, option_pr3_upET,
            option_ope_pr_downET, option_ope_pr_upET, option_ope_pr_timeET, option_sol_timeET, option_std_currentET, option_pr1_maxET, option_pr2_maxET, option_pr3_maxET,
            option_ct1_maxET, option_ct2_maxET, option_ct3_maxET, option_ntc_maxET, option_ntc_2_maxET, option_pt100_1_maxET, option_ope_rpm_minET, option_ope_rpm_maxET,
            option_fan_motor_start_tempET, option_fan_motor_stop_tempET, option_fan_motor_delay_timeET, option_main_ct_delayET,
            option_pr1_downET, option_pr2_downET, option_pr3_downET;
    private RadioGroup option_operationRG, option_modeRG;
    private LinearLayout inverterLL, fan_motorLL;
    private String mc_idx, cp_idx, mac, inverter_yn, inverter_mode, cp_airline;
    private MonitoringData monitoringData;
    private Context context;
    private boolean on_alarm_change = false;
    private TextView temp_pt100_signTV, temp_ntc_signTV, temp_ntc2_signTV;
    private ImageView temp_pt100_signIV, temp_ntc_signIV, temp_ntc2_signIV;

    private ProgressBar optionPB;
    private Thread timer_thread;

    private MqttAndroidClient option_mqttAndroidClient;

    @SuppressLint("ValidFragment")
    public Option_IoT_Fragment(Handler handler, String mc_idx, String cp_idx, String mac, String cp_airline) {
        this.handler = handler;
        this.mc_idx = mc_idx;
        this.cp_idx = cp_idx;
        this.mac = mac;
        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;
    }

    @Override
    public void onStop() {
        super.onStop();
        if (timer_thread != null) {
            timer_thread.interrupt();
            timer_thread = null;
        }

        if (option_mqttAndroidClient != null && option_mqttAndroidClient.isConnected())
            option_mqttAndroidClient = Common.getInstance().mqtt_disconnect(option_mqttAndroidClient);
    }

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

        option_ct1_upET = v.findViewById(R.id.option_ct1_upET);
        option_ct1_delayET = v.findViewById(R.id.option_ct1_delayET);
        option_ct2_upET = v.findViewById(R.id.option_ct2_upET);
        option_ct3_upET = v.findViewById(R.id.option_ct3_upET);
        option_ntc_downET = v.findViewById(R.id.option_ntc_downET);
        option_ntc_2_downET = v.findViewById(R.id.option_ntc_2_downET);
        option_pt_downET = v.findViewById(R.id.option_pt_downET);
        option_ntc_upET = v.findViewById(R.id.option_ntc_upET);
        option_ntc_2_upET = v.findViewById(R.id.option_ntc_2_upET);
        option_pt_upET = v.findViewById(R.id.option_pt_upET);
        option_pr1_upET = v.findViewById(R.id.option_pr1_upET);
        option_pr2_upET = v.findViewById(R.id.option_pr2_upET);
        option_pr3_upET = v.findViewById(R.id.option_pr3_upET);
        option_saveTV = v.findViewById(R.id.option_saveTV);
        option_operationRG = v.findViewById(R.id.option_operationRG);
        option_ope_pr_downET = v.findViewById(R.id.option_ope_pr_downET);
        option_ope_pr_upET = v.findViewById(R.id.option_ope_pr_upET);
        option_ope_pr_timeET = v.findViewById(R.id.option_ope_pr_timeET);
        optionPB = v.findViewById(R.id.optionPB);

        option_sol_timeET = v.findViewById(R.id.option_sol_timeET);
        option_std_currentET = v.findViewById(R.id.option_std_currentET);
        option_pr1_maxET = v.findViewById(R.id.option_pr1_maxET);
        option_pr2_maxET = v.findViewById(R.id.option_pr2_maxET);
        option_pr3_maxET = v.findViewById(R.id.option_pr3_maxET);
        option_ct1_maxET = v.findViewById(R.id.option_ct1_maxET);
        option_ct2_maxET = v.findViewById(R.id.option_ct2_maxET);
        option_ct3_maxET = v.findViewById(R.id.option_ct3_maxET);
        option_ntc_maxET = v.findViewById(R.id.option_ntc_maxET);
        option_ntc_2_maxET = v.findViewById(R.id.option_ntc_2_maxET);
        option_pt100_1_maxET = v.findViewById(R.id.option_pt100_1_maxET);
        option_machine_settingTV = v.findViewById(R.id.option_machine_settingTV);
        option_ope_rpm_minET = v.findViewById(R.id.option_ope_rpm_minET);
        option_ope_rpm_maxET = v.findViewById(R.id.option_ope_rpm_maxET);

        option_modeRG = v.findViewById(R.id.option_modeRG);
        option_operationRG = v.findViewById(R.id.option_operationRG);

        option_fan_motor_start_tempET = v.findViewById(R.id.option_fan_motor_start_tempET);
        option_fan_motor_stop_tempET = v.findViewById(R.id.option_fan_motor_stop_tempET);
        option_fan_motor_delay_timeET = v.findViewById(R.id.option_fan_motor_delay_timeET);
        inverterLL = v.findViewById(R.id.inverterLL);
        fan_motorLL = v.findViewById(R.id.fan_motorLL);
        option_main_ct_delayET = v.findViewById(R.id.option_main_ct_delayET);

        temp_pt100_signTV = v.findViewById(R.id.temp_pt100_signTV);
        temp_ntc_signTV = v.findViewById(R.id.temp_ntc_signTV);
        temp_ntc2_signTV = v.findViewById(R.id.temp_ntc2_signTV);
        temp_pt100_signIV = v.findViewById(R.id.temp_pt100_signIV);
        temp_ntc_signIV = v.findViewById(R.id.temp_ntc_signIV);
        temp_ntc2_signIV = v.findViewById(R.id.temp_ntc2_signIV);

        option_pr1_downET = v.findViewById(R.id.option_pr1_downET);
        option_pr2_downET = v.findViewById(R.id.option_pr2_downET);
        option_pr3_downET = v.findViewById(R.id.option_pr3_downET);

        option_interlock_settingTV = v.findViewById(R.id.option_interlock_settingTV);

        context = getActivity().getBaseContext();

        mqtt_connect();
        init_Handler();
        init_Listener();

        return v;
    }

    void Get_Machine() {

        String msg = "{'MAC' : '" + mac + "', 'opt' : 8}";
        JsonParser parser = new JsonParser();
        Object obj = parser.parse(msg);

        if (option_mqttAndroidClient != null) {
            Common.getInstance().publishMessage("control/" + mac, obj.toString(), option_mqttAndroidClient);

            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Common.getInstance().subscribeTopic("get_val/" + mac, option_mqttAndroidClient);
                }
            }, 300);

            timer_thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(5000);
                        if (fa != null) {
                            fa.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Common.getInstance().unSubscribeTopic("get_val/" + mac, option_mqttAndroidClient);
                                    Common.getInstance().toastShow(context, "MQTT 서버가 연결되어 있지 않습니다. 잠시 후 다시 시도해주세요.");
                                    optionPB.setVisibility(View.GONE);

                                    getActivity().finish();
                                }
                            });
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            });

            timer_thread.start();

        } else {
            Common.getInstance().toastShow(context, "MQTT 서버가 연결되어 있지 않습니다. 잠시 후 다시 시도해주세요.");
            fa.finish();
        }
    }

    void Set_Content() {

        if (monitoringData == null) {
            Common.getInstance().toastShow(context, "IoT 기기에서 정보를 불러오지 못했습니다.\n잠시후 다시 시도해주세요.");
            fa.finish();
            return;
        }

        if (monitoringData.getInverterMode() != null && monitoringData.getInverterMode().equals("1")) {
            inverter_yn = "Y";
            option_operationRG.check(R.id.option_inverterRBtn);
            inverterLL.setVisibility(View.VISIBLE);
            fan_motorLL.setVisibility(View.GONE);

        } else {
            inverter_yn = "N";
            option_operationRG.check(R.id.option_ydRBtn);
            inverterLL.setVisibility(View.GONE);
            fan_motorLL.setVisibility(View.VISIBLE);
        }

        if (monitoringData.getInverterSpeed() != null && monitoringData.getInverterSpeed().equals("1")) {
            inverter_mode = "1";
            option_modeRG.check(R.id.option_ecoRBtn);

        } else if (monitoringData.getInverterSpeed() != null && monitoringData.getInverterSpeed().equals("2")) {
            inverter_mode = "2";
            option_modeRG.check(R.id.option_speedRBtn);

        } else {
            inverter_mode = "3";
            option_modeRG.check(R.id.option_normalRBtn);
        }

        option_ct1_upET.setText(monitoringData.getMcCurrent1Up());
        option_ct1_maxET.setText(monitoringData.getCurrent1Max());
        option_ct2_upET.setText(monitoringData.getMcCurrent2Up());
        option_ct2_maxET.setText(monitoringData.getCurrent2Max());
        option_ct3_upET.setText(monitoringData.getMcCurrent3Up());
        option_ct3_maxET.setText(monitoringData.getCurrent3Max());

        option_ntc_maxET.setText(monitoringData.getTempNtcMax());
        option_ntc_2_maxET.setText(monitoringData.getTempNtc2Max());
        option_pt100_1_maxET.setText(monitoringData.getTempPt100Max());

        option_ntc_downET.setText(monitoringData.getMcTempNtcDown());
        option_ntc_2_downET.setText(monitoringData.getMcTempNtc2Down());
        option_pt_downET.setText(monitoringData.getMcTempPtDown());

        if (monitoringData.getMcTempNtcDown().contains("-")) {
            temp_ntc_signIV.setImageResource(R.drawable.icon_plus2);
            temp_ntc_signTV.setText("-");
            option_ntc_downET.setText(monitoringData.getMcTempNtcDown().substring(1));
        } else {
            temp_ntc_signIV.setImageResource(R.drawable.icon_minus);
            temp_ntc_signTV.setText("+");
        }

        if (monitoringData.getMcTempNtc2Down().contains("-")) {
            temp_ntc2_signIV.setImageResource(R.drawable.icon_plus2);
            temp_ntc2_signTV.setText("-");
            option_ntc_2_downET.setText(monitoringData.getMcTempNtc2Down().substring(1));
        } else {
            temp_ntc2_signIV.setImageResource(R.drawable.icon_minus);
            temp_ntc2_signTV.setText("+");
        }

        if (monitoringData.getMcTempPtDown().contains("-")) {
            temp_pt100_signIV.setImageResource(R.drawable.icon_plus2);
            temp_pt100_signTV.setText("-");
            option_pt_downET.setText(monitoringData.getMcTempPtDown().substring(1));
        } else {
            temp_pt100_signIV.setImageResource(R.drawable.icon_minus);
            temp_pt100_signTV.setText("+");
        }

        option_ntc_upET.setText(monitoringData.getMcTempNtcUp());
        option_ntc_2_upET.setText(monitoringData.getMcTempNtc2Up());
        option_pt_upET.setText(monitoringData.getMcTempPtUp());

        option_pr1_maxET.setText(Common.getInstance().isNullToZeroFloat(monitoringData.getPressure1Max()));
        option_pr2_maxET.setText(Common.getInstance().isNullToZeroFloat(monitoringData.getPressure2Max()));
        option_pr3_maxET.setText(Common.getInstance().isNullToZeroFloat(monitoringData.getPressure3Max()));
        option_pr1_maxET.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(3, 1)});
        option_pr2_maxET.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(3, 1)});
        option_pr3_maxET.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(3, 1)});

        option_pr1_upET.setText(Common.getInstance().isNullToZeroFloat(monitoringData.getMcPressure1Up()));
        option_pr1_upET.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(3, 1)});
        option_pr2_upET.setText(Common.getInstance().isNullToZeroFloat(monitoringData.getMcPressure2Up()));
        option_pr2_upET.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(3, 1)});
        option_pr3_upET.setText(Common.getInstance().isNullToZeroFloat(monitoringData.getMcPressure3Up()));
        option_pr3_upET.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(3, 1)});

        option_pr1_downET.setText(Common.getInstance().isNullToZeroFloat(monitoringData.getMcPressure1Down()));
        option_pr1_downET.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(3, 1)});
        option_pr2_downET.setText(Common.getInstance().isNullToZeroFloat(monitoringData.getMcPressure2Down()));
        option_pr2_downET.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(3, 1)});
        option_pr3_downET.setText(Common.getInstance().isNullToZeroFloat(monitoringData.getMcPressure3Down()));
        option_pr3_downET.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(3, 1)});

        option_sol_timeET.setText(Integer.parseInt(monitoringData.getRelay2Time()) / 1000 + "");
        option_ope_pr_downET.setText(Common.getInstance().isNullToZeroFloat(monitoringData.getPressureMin()));
        option_ope_pr_upET.setText(Common.getInstance().isNullToZeroFloat(monitoringData.getPressureMax()));
        option_ope_rpm_minET.setText(Common.getInstance().isNullToZeroFloat(monitoringData.getRpmMin()));
        option_ope_rpm_maxET.setText(Common.getInstance().isNullToZeroFloat(monitoringData.getRpmMax()));
        option_std_currentET.setText(monitoringData.getStdCurrent());
        option_ct1_delayET.setText(monitoringData.getCurrentDelay());
        option_ope_pr_timeET.setText(Integer.parseInt(monitoringData.getPressureTime()) / 60000 + "");
        if (monitoringData.getMainCurrentDelayTime() != null && Integer.parseInt(monitoringData.getMainCurrentDelayTime()) < 0) {
            option_main_ct_delayET.setText("0");
        } else {
            option_main_ct_delayET.setText(Integer.parseInt(monitoringData.getMainCurrentDelayTime()) / 1000 + "");
        }

        option_fan_motor_start_tempET.setText(monitoringData.getFanMotorStartTemp());
        option_fan_motor_stop_tempET.setText(monitoringData.getFanMotorStopTemp());
        option_fan_motor_delay_timeET.setText(monitoringData.getFanMotorDelayTime());

    }

    void init_Listener() {

        //기동설정 클릭 리스너
        option_operationRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Button button = group.findViewById(checkedId);
                switch (button.getText().toString()) {
                    case "Y-D":
                        inverter_yn = "N";
                        inverterLL.setVisibility(View.GONE);
                        fan_motorLL.setVisibility(View.VISIBLE);
                        break;
                    case "INVERTER":
                        inverter_yn = "Y";
                        inverterLL.setVisibility(View.VISIBLE);
                        fan_motorLL.setVisibility(View.GONE);
                        break;
                }
            }
        });

        //운전모드 클릭 리스너
        option_modeRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Button button = group.findViewById(checkedId);
                switch (button.getText().toString()) {
                    case "ECO":
                        inverter_mode = "1";
                        break;
                    case "SPEED":
                        inverter_mode = "2";
                        break;
                    case "NORMAL":
                        inverter_mode = "3";
                        break;
                }
            }
        });

        //온도 센서 부호 클릭 리스너
        temp_pt100_signIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (temp_pt100_signTV.getText().equals("-")) {
                    temp_pt100_signTV.setText("+");
                    temp_pt100_signIV.setImageResource(R.drawable.icon_minus);
                } else {
                    temp_pt100_signTV.setText("-");
                    temp_pt100_signIV.setImageResource(R.drawable.icon_plus2);
                }
            }
        });

        //ntc 부호
        temp_ntc_signIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (temp_ntc_signTV.getText().equals("-")) {
                    temp_ntc_signTV.setText("+");
                    temp_ntc_signIV.setImageResource(R.drawable.icon_minus);
                } else {
                    temp_ntc_signTV.setText("-");
                    temp_ntc_signIV.setImageResource(R.drawable.icon_plus2);
                }
            }
        });

        //ntc2 부호
        temp_ntc2_signIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (temp_ntc2_signTV.getText().equals("-")) {
                    temp_ntc2_signTV.setText("+");
                    temp_ntc2_signIV.setImageResource(R.drawable.icon_minus);
                } else {
                    temp_ntc2_signTV.setText("-");
                    temp_ntc2_signIV.setImageResource(R.drawable.icon_plus2);
                }
            }
        });

        //저장버튼 클릭 리스너
        option_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                option_saveTV.setEnabled(false);
                optionPB.setVisibility(View.VISIBLE);
                save_option();
            }
        });

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

                if (optionPB.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);
            }
        });

        //연동제어 설정 클릭리스너
        option_interlock_settingTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (optionPB.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_interlock");
                intent.putExtra("value1", cp_idx);
                intent.putExtra("value2", mc_idx);
                intent.putExtra("value3", cp_airline);
                fa.finish();
                startActivity(intent);
            }
        });

    }

    void save_option() {

        if (option_mqttAndroidClient == null) {
            Common.getInstance().toastShow(context, "MQTT 서버가 연결되어 있지 않습니다. 잠시 후 다시 시도해주세요.");
            mqtt_connect();
            return;
        }

        String mc_current1_up = Common.getInstance().isNullToZero(option_ct1_upET.getText().toString());
        String mc_current2_up = Common.getInstance().isNullToZero(option_ct2_upET.getText().toString());
        String mc_current3_up = Common.getInstance().isNullToZero(option_ct3_upET.getText().toString());

        String main_current_delay = Common.getInstance().isNullToZero(option_main_ct_delayET.getText().toString());
        String current_delay = Common.getInstance().isNullToZero(option_ct1_delayET.getText().toString());

        String mc_temp_ntc_down = Common.getInstance().isNullToZero(option_ntc_downET.getText().toString());
        String mc_temp_ntc_up = Common.getInstance().isNullToZero(option_ntc_upET.getText().toString());
        String mc_temp_ntc_2_down = Common.getInstance().isNullToZero(option_ntc_2_downET.getText().toString());
        String mc_temp_ntc_2_up = Common.getInstance().isNullToZero(option_ntc_2_upET.getText().toString());
        String mc_temp_pt_down = Common.getInstance().isNullToZero(option_pt_downET.getText().toString());
        String mc_temp_pt_up = Common.getInstance().isNullToZero(option_pt_upET.getText().toString());

        if (temp_ntc_signTV.getText().equals("-")) mc_temp_ntc_down = "-" + mc_temp_ntc_down;
        if (temp_ntc2_signTV.getText().equals("-")) mc_temp_ntc_2_down = "-" + mc_temp_ntc_2_down;
        if (temp_pt100_signTV.getText().equals("-")) mc_temp_pt_down = "-" + mc_temp_pt_down;

        String mc_pressure1_up = Common.getInstance().isNullToZeroFloat(option_pr1_upET.getText().toString());
        String mc_pressure2_up = Common.getInstance().isNullToZeroFloat(option_pr2_upET.getText().toString());
        String mc_pressure3_up = Common.getInstance().isNullToZeroFloat(option_pr3_upET.getText().toString());

        String mc_pressure1_down = Common.getInstance().isNullToZeroFloat(option_pr1_downET.getText().toString());
        String mc_pressure2_down = Common.getInstance().isNullToZeroFloat(option_pr2_downET.getText().toString());
        String mc_pressure3_down = Common.getInstance().isNullToZeroFloat(option_pr3_downET.getText().toString());

        //절전모드 시간
        String press_time = Common.getInstance().isNullText(option_ope_pr_timeET.getText().toString());
        //sol 시간
        String sol_time = Common.getInstance().isNullText(option_sol_timeET.getText().toString());
        String pressure_min = Common.getInstance().isNullToZeroFloat(option_ope_pr_downET.getText().toString());
        String pressure_max = Common.getInstance().isNullToZeroFloat(option_ope_pr_upET.getText().toString());
        String rpm_min = Common.getInstance().isNullText(option_ope_rpm_minET.getText().toString());
        String rpm_max = Common.getInstance().isNullText(option_ope_rpm_maxET.getText().toString());

        String fan_motor_start_temp = Common.getInstance().isNullText(option_fan_motor_start_tempET.getText().toString());
        String fan_motor_stop_temp = Common.getInstance().isNullText(option_fan_motor_stop_tempET.getText().toString());
        String fan_motor_delay_time = Common.getInstance().isNullText(option_fan_motor_delay_timeET.getText().toString());

        //IoT 알람설정 모드
        //주의 구간 설정
        String ct1_up = Common.getInstance().convert_mqtt_value_string("mc_current1_up", mc_current1_up);
        String ct2_up = Common.getInstance().convert_mqtt_value_string("mc_current2_up", mc_current2_up);
        String ct3_up = Common.getInstance().convert_mqtt_value_string("mc_current3_up", mc_current3_up);

        String temp_ntc_up = Common.getInstance().convert_mqtt_value_string("mc_temp_ntc_up", mc_temp_ntc_up);
        String temp_ntc_down = Common.getInstance().convert_mqtt_value_string("mc_temp_ntc_down", mc_temp_ntc_down);
        String temp_ntc_2_up = Common.getInstance().convert_mqtt_value_string("mc_temp_ntc_2_up", mc_temp_ntc_2_up);
        String temp_ntc_2_down = Common.getInstance().convert_mqtt_value_string("mc_temp_ntc_2_down", mc_temp_ntc_2_down);
        String temp_pt_up = Common.getInstance().convert_mqtt_value_string("mc_temp_pt_up", mc_temp_pt_up);
        String temp_pt_down = Common.getInstance().convert_mqtt_value_string("mc_temp_pt_down", mc_temp_pt_down);
        String pr1_up = Common.getInstance().convert_mqtt_value_string("mc_pressure1_up", mc_pressure1_up);
        String pr2_up = Common.getInstance().convert_mqtt_value_string("mc_pressure2_up", mc_pressure2_up);
        String pr3_up = Common.getInstance().convert_mqtt_value_string("mc_pressure3_up", mc_pressure3_up);
        String pr1_down = Common.getInstance().convert_mqtt_value_string("mc_pressure1_down", mc_pressure1_down);
        String pr2_down = Common.getInstance().convert_mqtt_value_string("mc_pressure2_down", mc_pressure2_down);
        String pr3_down = Common.getInstance().convert_mqtt_value_string("mc_pressure3_down", mc_pressure3_down);

        String main_ct_delay = "'main_current_delay_time' : " + (Integer.parseInt(main_current_delay) * 1000) + "";
        String ct_delay = "'current_delay' : '" + current_delay + "'";
        String std_current = Common.getInstance().convert_mqtt_value_string("std_current", option_std_currentET.getText().toString());

        String pressure1_max = Common.getInstance().convert_mqtt_value_string("mc_pressure1_max", Common.getInstance().isNullToZeroFloat(option_pr1_maxET.getText().toString()));
        String pressure2_max = Common.getInstance().convert_mqtt_value_string("mc_pressure2_max", Common.getInstance().isNullToZeroFloat(option_pr2_maxET.getText().toString()));
        String pressure3_max = Common.getInstance().convert_mqtt_value_string("mc_pressure3_max", Common.getInstance().isNullToZeroFloat(option_pr3_maxET.getText().toString()));
        String current1_max = Common.getInstance().convert_mqtt_value_string("mc_current1_max", option_ct1_maxET.getText().toString());
        String current2_max = Common.getInstance().convert_mqtt_value_string("mc_current2_max", option_ct2_maxET.getText().toString());
        String current3_max = Common.getInstance().convert_mqtt_value_string("mc_current3_max", option_ct3_maxET.getText().toString());
        String temp_ntc_max = Common.getInstance().convert_mqtt_value_string("mc_temp_ntc_max", option_ntc_maxET.getText().toString());
        String temp_ntc_2_max = Common.getInstance().convert_mqtt_value_string("mc_temp_ntc_2_max", option_ntc_2_maxET.getText().toString());
        String temp_pt_max = Common.getInstance().convert_mqtt_value_string("mc_temp_pt100_max", option_pt100_1_maxET.getText().toString());

        //절전모드 시간
        if (press_time.equals("")) press_time = "0";
        press_time = Common.getInstance().convert_mqtt_value_string("pressure_time", (Integer.parseInt(press_time) * 60000) + "");

        //sol 시간
        if (sol_time.equals("")) sol_time = "0";
        sol_time = Common.getInstance().convert_mqtt_value_string("relay2_time", (Integer.parseInt(sol_time) * 1000) + "");
        pressure_min = Common.getInstance().convert_mqtt_value_string("pressure_min", pressure_min);
        pressure_max = Common.getInstance().convert_mqtt_value_string("pressure_max", pressure_max);
        rpm_min = Common.getInstance().convert_mqtt_value_string("rpm_min", rpm_min);
        rpm_max = Common.getInstance().convert_mqtt_value_string("rpm_max", rpm_max);

        fan_motor_start_temp = Common.getInstance().convert_mqtt_value_string("fan_motor_start_temp", fan_motor_start_temp);
        fan_motor_stop_temp = Common.getInstance().convert_mqtt_value_string("fan_motor_stop_temp", fan_motor_stop_temp);
        fan_motor_delay_time = Common.getInstance().convert_mqtt_value_string("fan_motor_delay_time", fan_motor_delay_time);

        String inverter_speed = "";
        if (inverter_mode == null) {
            inverter_speed = "";
        } else {
            inverter_speed = "'inverter_speed' : '" + inverter_mode + "'";
        }

        String[] values = new String[]{ct1_up, ct2_up, ct3_up, temp_ntc_up, temp_ntc_down, temp_ntc_2_up, temp_ntc_2_down, temp_pt_up, temp_pt_down,
                pr1_up, pr2_up, pr3_up, ct_delay, inverter_speed, std_current, main_ct_delay, press_time, sol_time, pressure_min, pressure_max, rpm_min, rpm_max, fan_motor_start_temp,
                fan_motor_stop_temp, fan_motor_delay_time, pressure1_max, pressure2_max, pressure3_max, current1_max, current2_max, current3_max,
                temp_ntc_max, temp_ntc_2_max, temp_pt_max, pr1_down, pr2_down, pr3_down};

        String alarm_setting = "";

        for (int i = 0; i < values.length; i++) {
            if (i > 0 && values[i] != null && !values[i].equals("")) {
                alarm_setting += ", " + values[i];
            } else if (i == 0 && values[i] != null && !values[i].equals("")) {
                alarm_setting = values[i];
            }
        }
        String msg = "";

        if (inverter_yn.equals("Y")) {
            msg = "{'MAC' : '" + mac + "', 'opt' : 1, 'inverter_mode' : 1," + alarm_setting + "}";
        } else {
            msg = "{'MAC' : '" + mac + "', 'opt' : 1, 'inverter_mode' : 2," + alarm_setting + "}";
        }
        JsonParser parser = new JsonParser();
        Object obj = parser.parse(msg);

        Log.d("보냈어영@@@@@", msg);

        on_alarm_change = true;

        if (option_mqttAndroidClient == null) {
            Common.getInstance().toastShow(context, "MQTT 서버가 연결되어 있지 않습니다. 잠시 후 다시 시도해주세요.");
            mqtt_connect();
            return;
        }

        Common.getInstance().publishMessage("control/" + mac, obj.toString(), option_mqttAndroidClient);
        Common.getInstance().subscribeTopic("check/" + mac, option_mqttAndroidClient);


        timer_thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    if (fa != null) {
                        fa.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Common.getInstance().unSubscribeTopic("check/" + mac, option_mqttAndroidClient);
                                Common.getInstance().toastShow(context, "OPT_1 CNT 센서값 읽기에 실패했습니다.\n잠시후 다시 시도해주세요.");
                                getActivity().finish();
                            }
                        });
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        timer_thread.start();
    }

    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_admin_machine_alarm_option")) {
                        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();

                        } else {
                            Toast.makeText(getContext(), "데이터 저장에 실패했습니다.", Toast.LENGTH_SHORT).show();
                        }
                        option_saveTV.setEnabled(true);
                    }

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

    @Override
    public void onResume() {
        super.onResume();
        if (option_mqttAndroidClient == null) {
            mqtt_connect();

        } else {

            optionPB.setVisibility(View.VISIBLE);
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Get_Machine();
                }
            }, 1500);
        }
    }

    void mqtt_connect() {

        if (option_mqttAndroidClient == null) {
            option_mqttAndroidClient = Common.getInstance().mqtt_connect(getContext(), option_mqttAndroidClient);
        }

        option_mqttAndroidClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                Log.i("@@@", "옵션 connectionLost");
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {

                JsonParser parser = new JsonParser();
                JsonObject jsonObject = (JsonObject) parser.parse(new String(message.getPayload()));
                monitoringData = new Gson().fromJson(jsonObject, new TypeToken<MonitoringData>() {
                }.getType());

                optionPB.setVisibility(View.GONE);

                if (topic.contains("check")) {

                    if (monitoringData.getOpt1Cnt() != null && monitoringData.getOpt1Cnt().equals("1") && on_alarm_change) {

                        if (timer_thread != null) {
                            timer_thread.interrupt();
                            timer_thread = null;
                        }

                        //서비스 접수 구간 설정
                        on_alarm_change = false;
                        Common.getInstance().unSubscribeTopic(topic, option_mqttAndroidClient);

                        String current_delay = Common.getInstance().isNullToZero(option_ct1_delayET.getText().toString());
                        String mc_std_current = Common.getInstance().isNullToZero(option_std_currentET.getText().toString());
                        String mc_current1_up = Common.getInstance().isNullToZero(option_ct1_upET.getText().toString());
                        String mc_current2_up = Common.getInstance().isNullToZero(option_ct2_upET.getText().toString());
                        String mc_current3_up = Common.getInstance().isNullToZero(option_ct3_upET.getText().toString());
                        String mc_temp_ntc_down = Common.getInstance().isNullToZero(option_ntc_downET.getText().toString());
                        String mc_temp_ntc_up = Common.getInstance().isNullToZero(option_ntc_upET.getText().toString());
                        String mc_temp_ntc_2_down = Common.getInstance().isNullToZero(option_ntc_2_downET.getText().toString());
                        String mc_temp_ntc_2_up = Common.getInstance().isNullToZero(option_ntc_2_upET.getText().toString());
                        String mc_temp_pt_down = Common.getInstance().isNullToZero(option_pt_downET.getText().toString());
                        if (temp_ntc_signTV.getText().equals("-"))
                            mc_temp_ntc_down = "-" + mc_temp_ntc_down;
                        if (temp_ntc2_signTV.getText().equals("-"))
                            mc_temp_ntc_2_down = "-" + mc_temp_ntc_2_down;
                        if (temp_pt100_signTV.getText().equals("-"))
                            mc_temp_pt_down = "-" + mc_temp_pt_down;

                        String mc_temp_pt_up = Common.getInstance().isNullToZero(option_pt_upET.getText().toString());
                        String mc_pressure1_up = Common.getInstance().isNullToZeroFloat(option_pr1_upET.getText().toString());
                        String mc_pressure2_up = Common.getInstance().isNullToZeroFloat(option_pr2_upET.getText().toString());
                        String mc_pressure3_up = Common.getInstance().isNullToZeroFloat(option_pr3_upET.getText().toString());
                        String mc_pressure1_down = Common.getInstance().isNullToZeroFloat(option_pr1_downET.getText().toString());
                        String mc_pressure2_down = Common.getInstance().isNullToZeroFloat(option_pr2_downET.getText().toString());
                        String mc_pressure3_down = Common.getInstance().isNullToZeroFloat(option_pr3_downET.getText().toString());
                        String pressure1_max = Common.getInstance().isNullToZeroFloat(option_pr1_maxET.getText().toString());
                        String pressure2_max = Common.getInstance().isNullToZeroFloat(option_pr2_maxET.getText().toString());
                        String pressure3_max = Common.getInstance().isNullToZeroFloat(option_pr3_maxET.getText().toString());
                        String current1_max = Common.getInstance().isNullToZero(option_ct1_maxET.getText().toString());
                        String current2_max = Common.getInstance().isNullToZero(option_ct2_maxET.getText().toString());
                        String current3_max = Common.getInstance().isNullToZero(option_ct3_maxET.getText().toString());
                        String temp_ntc_max = Common.getInstance().isNullToZero(option_ntc_maxET.getText().toString());
                        String temp_ntc_2_max = Common.getInstance().isNullToZero(option_ntc_2_maxET.getText().toString());
                        String temp_pt_max = Common.getInstance().isNullToZero(option_pt100_1_maxET.getText().toString());
                        //절전모드 시간
                        String press_time = Common.getInstance().isNullText(option_ope_pr_timeET.getText().toString());
                        //sol 시간
                        String mc_sol_time = Common.getInstance().isNullText(option_sol_timeET.getText().toString());
                        String pressure_min = Common.getInstance().isNullToZeroFloat(option_ope_pr_downET.getText().toString());
                        String pressure_max = Common.getInstance().isNullToZeroFloat(option_ope_pr_upET.getText().toString());
                        String rpm_min = Common.getInstance().isNullText(option_ope_rpm_minET.getText().toString());
                        String rpm_max = Common.getInstance().isNullText(option_ope_rpm_maxET.getText().toString());

                        String fan_motor_start_temp = Common.getInstance().isNullText(option_fan_motor_start_tempET.getText().toString());
                        String fan_motor_stop_temp = Common.getInstance().isNullText(option_fan_motor_stop_tempET.getText().toString());
                        String fan_motor_delay_time = Common.getInstance().isNullText(option_fan_motor_delay_timeET.getText().toString());

                        HashMap<String, String> data = new HashMap<>();
                        data.put("mc_idx", mc_idx);
                        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                        data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
                        data.put("cp_idx", cp_idx);

                        data.put("mc_inverter_yn", inverter_yn);
                        data.put("mc_current1_up", mc_current1_up);
                        data.put("mc_current2_up", mc_current2_up);
                        data.put("mc_current3_up", mc_current3_up);
                        data.put("current_delay", current_delay);
                        data.put("mc_std_current", mc_std_current);
                        data.put("mc_temp_ntc_down", mc_temp_ntc_down);
                        data.put("mc_temp_ntc_up", mc_temp_ntc_up);
                        data.put("mc_temp_ntc_2_down", mc_temp_ntc_2_down);
                        data.put("mc_temp_ntc_2_up", mc_temp_ntc_2_up);
                        data.put("mc_temp_pt_down", mc_temp_pt_down);
                        data.put("mc_temp_pt_up", mc_temp_pt_up);
                        data.put("mc_pressure1_up", mc_pressure1_up);
                        data.put("mc_pressure2_up", mc_pressure2_up);
                        data.put("mc_pressure3_up", mc_pressure3_up);
                        data.put("mc_pressure1_down", mc_pressure1_down);
                        data.put("mc_pressure2_down", mc_pressure2_down);
                        data.put("mc_pressure3_down", mc_pressure3_down);

                        data.put("mc_current1_max", current1_max);
                        data.put("mc_current2_max", current2_max);
                        data.put("mc_current3_max", current3_max);
                        data.put("mc_pressure1_max", pressure1_max);
                        data.put("mc_pressure2_max", pressure2_max);
                        data.put("mc_pressure3_max", pressure3_max);
                        data.put("mc_temp_ntc_max", temp_ntc_max);
                        data.put("mc_temp_ntc_2_max", temp_ntc_2_max);
                        data.put("mc_temp_pt_max", temp_pt_max);

                        data.put("press_time", press_time);
                        data.put("mc_sol_time", mc_sol_time);
                        data.put("mc_press_x", pressure_min);
                        data.put("mc_press_y", pressure_max);
                        data.put("mc_rpm_min", rpm_min);
                        data.put("mc_rpm_max", rpm_max);
                        data.put("mc_fan_motor_start_temp", fan_motor_start_temp);
                        data.put("mc_fan_motor_stop_temp", fan_motor_stop_temp);
                        data.put("mc_fan_motor_delay_time", fan_motor_delay_time);
                        data.put("mc_inverter_mode", inverter_mode);

                        new ApiClient(data, "proc_admin_machine_alarm_option", handler);
                    }
                } else if (topic.contains("get_val")) {

                    if (timer_thread != null) {
                        timer_thread.interrupt();
                        timer_thread = null;
                    }

                    Common.getInstance().unSubscribeTopic(topic, option_mqttAndroidClient);
                    Set_Content();
                }
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                Log.d("deliveryComplete@@@@", token.toString());
            }
        });
    }
}
