package kr.co.compcarecompany.Fragment;

import static kr.co.compcarecompany.Activity.ActivityBasic.userItem;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
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.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
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 org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import info.mqtt.android.service.MqttAndroidClient;
import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.Product.MonitoringData;
import kr.co.compcarecompany.Data.Product.RelayData;
import kr.co.compcarecompany.MyApplication;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.RelayScheduleAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.CustomView.AddScheduleDialog2;
import kr.co.compcarecompany.Util.CustomView.MachinePasswordDialog;

public class Relay_Schedule2_Fragment extends Fragment {

    private Handler handler;
    private FragmentActivity fa;

    private LinearLayout schedule_addLL, schedule_modeLL, schedule_editLL, schedule_activeLL, schedule_edit_closeLL;
    private RecyclerView relay_scheduleRV;
    private RelayScheduleAdapter adapter;
    private boolean edit_mode = false;
    private boolean schedule_active = false;
    private ArrayItem<RelayData> relay_array = new ArrayItem<>();
    private String mc_idx, mc_iot_mac, mc_schedule_yn;
    private TextView schedule_mainTV, schedule_saveTV, schedule_editTV, schedule_modeTV, schedule_activeTV;
    private ArrayList<String> del_list = new ArrayList<>();
    private ArrayList<RelayData> add_list = new ArrayList<>();
    private ArrayList<RelayData> relay_list = new ArrayList<>();
    private boolean on_active = false;
    private boolean on_save = false;
    private boolean on_schedule_save = false;
    private HashMap<String, String> save_schedule_data;
    private ImageView schedule_activeIV;
    private Thread timer_thread;
    private ProgressDialog progressDialog;
    private MqttAndroidClient schedule_mqttAndroidClient;

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

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

    @SuppressLint("ValidFragment")
    public Relay_Schedule2_Fragment(Handler handler, String mc_idx, String mc_iot_mac, String mc_schedule_yn) {
        this.handler = handler;
        this.mc_idx = mc_idx;
        this.mc_iot_mac = mc_iot_mac;
        this.mc_schedule_yn = mc_schedule_yn;
    }

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

        schedule_addLL = v.findViewById(R.id.schedule_addLL);
        relay_scheduleRV = v.findViewById(R.id.relay_scheduleRV);
        schedule_mainTV = v.findViewById(R.id.schedule_mainTV);
        schedule_modeLL = v.findViewById(R.id.schedule_modeLL);
        schedule_editLL = v.findViewById(R.id.schedule_editLL);
        schedule_saveTV = v.findViewById(R.id.schedule_saveTV);
        schedule_modeTV = v.findViewById(R.id.schedule_modeTV);
        schedule_activeLL = v.findViewById(R.id.schedule_activeLL);
        schedule_activeTV = v.findViewById(R.id.schedule_activeTV);
        schedule_activeIV = v.findViewById(R.id.schedule_activeIV);

        schedule_mainTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_blue));

        if (mc_schedule_yn.equals("Y")) {
            final Animation animation = new AlphaAnimation(1, 0);
            animation.setDuration(1500);
            animation.setInterpolator(new LinearInterpolator());
            animation.setRepeatCount(Animation.INFINITE);
            animation.setRepeatMode(Animation.RESTART);
            schedule_activeIV.startAnimation(animation);
            schedule_activeIV.setImageResource(R.drawable.icon_power_green);
            schedule_activeTV.setText("스케줄 운전");
            schedule_active = true;

        } else {
            schedule_activeIV.setImageResource(R.drawable.icon_power_red);
            schedule_activeIV.clearAnimation();
            schedule_activeTV.setText("스케줄 정지");
            schedule_active = false;
        }

        adapter = new RelayScheduleAdapter(getContext(), edit_mode, schedule_active);
        relay_scheduleRV.setAdapter(adapter);

        init_Handler();
        init_Listener();
        get_relay_schedule();

        mqtt_connect();

        return v;
    }


    void get_relay_schedule() {

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

        new ApiClient(data, "proc_get_relay_schedule", handler);
    }

    public void init_Listener() {

        //스케줄 표 모드
        schedule_modeLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                edit_mode = false;
                adapter = new RelayScheduleAdapter(getContext(), edit_mode, schedule_active);
                adapter.addItems(relay_array.getArrayitem());
                relay_scheduleRV.setAdapter(adapter);
                relay_list.clear();
                add_list.clear();
                del_list.clear();

                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "원격운전 스케줄 표");
                intent.putExtra("type", "relay_schedule2");
                intent.putExtra("value1", relay_array.getArrayitem());
                startActivity(intent);
            }
        });

        //스케줄 편집 버튼 클릭 리스너
        schedule_editLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                schedule_editLL.setVisibility(View.GONE);

                edit_mode = true;
                relay_list.clear();
                relay_list.addAll(relay_array.getArrayitem());

                adapter = new RelayScheduleAdapter(getContext(), edit_mode, schedule_active, new RelayScheduleAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(HashMap<String, String> data) {
                        if (data.get("rs_idx") != null) {
                            del_list.add(data.get("rs_idx"));
                        }
                        relay_list.remove(Integer.parseInt(data.get("position")));
                        adapter.addItems(relay_list);
                    }
                });

                relay_scheduleRV.setAdapter(adapter);
                adapter.addItems(relay_list);

                schedule_saveTV.setVisibility(View.VISIBLE);
                schedule_addLL.setVisibility(View.VISIBLE);
                schedule_activeLL.setVisibility(View.GONE);
            }
        });

        //메인화면 클릭 리스너
        schedule_mainTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                schedule_mainTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_blue));
                schedule_modeTV.setTextColor(Color.BLACK);

                edit_mode = false;
                adapter = new RelayScheduleAdapter(getContext(), edit_mode, schedule_active);
                adapter.addItems(relay_array.getArrayitem());
                relay_scheduleRV.setAdapter(adapter);
                relay_list.clear();
                add_list.clear();
                del_list.clear();

                schedule_saveTV.setVisibility(View.GONE);
                schedule_addLL.setVisibility(View.GONE);
                schedule_activeLL.setVisibility(View.VISIBLE);
                schedule_activeLL.setEnabled(true);
                schedule_editLL.setVisibility(View.VISIBLE);
            }
        });

        //스케줄 활성/비활성 버튼 클릭 리스너
        schedule_activeLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //기계보안 비밀번호가 없을 경우 비밀번호 설정 페이지로 넘어감 //2021.04.05 수정
                if (userItem.getArrayitem().getPartner().getPtMachinePw() == null || userItem.getArrayitem().getPartner().getPtMachinePw().equals("")) {

                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("설정된 기계보안 비밀번호가 없습니다.\n바로 설정하시겠습니까?");
                    dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {

                            Intent intent = new Intent(getContext(), FragmentActivity.class);
                            intent.putExtra("title", "기계보안");
                            intent.putExtra("type", "password_setting");
                            intent.putExtra("value1", userItem.getArrayitem().getPartner().getPtMachinePw());
                            startActivity(intent);
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.show();

                } else {

                    //기계 비밀번호 확인 다이얼로그
                    MachinePasswordDialog dialog = new MachinePasswordDialog(getContext(), userItem.getArrayitem().getPartner().getPtMachinePw(), new MachinePasswordDialog.MachinePasswordDialogListener() {
                        @Override
                        public void clickBtn(boolean matched_pw) {

                            //비밀번호가 일치했을 경우
                            if (matched_pw) {

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

                                progressDialog = new ProgressDialog(getContext());
                                schedule_activeLL.setEnabled(false);
                                progressDialog.setIndeterminate(true);

                                String mode = "";
                                if (mc_schedule_yn.equals("Y")) {
                                    mc_schedule_yn = "N";
                                    mode = "3";
                                    progressDialog.setMessage("스케줄 비활성화 중입니다...");

                                } else {
                                    mc_schedule_yn = "Y";
                                    mode = "2";
                                    progressDialog.setMessage("스케줄 활성화 중입니다...");
                                }

                                String msg = "{'MAC' : '" + mc_iot_mac + "', 'opt' : 6, 'mode' : '" + mode + "'}";
                                JsonParser get_parser = new JsonParser();
                                Object obj = get_parser.parse(msg);

                                Common.getInstance().publishMessage("control/" + mc_iot_mac, obj.toString(), schedule_mqttAndroidClient);
                                Common.getInstance().subscribeTopic("check/" + mc_iot_mac, schedule_mqttAndroidClient);
                                on_active = true;
                                progressDialog.show();

                                timer_thread = new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            Thread.sleep(2000);
                                            if (fa != null) {
                                                fa.runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Common.getInstance().unSubscribeTopic("check/" + mc_iot_mac, schedule_mqttAndroidClient);
                                                        Common.getInstance().toastShow(getContext(), "스케줄 저장에 실패했습니다.\nIoT 기기의 인터넷 연결을 확인해주세요.");
                                                        progressDialog.dismiss();
                                                    }
                                                });
                                            }
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }

                                    }
                                });

                                timer_thread.start();

                            }
                        }
                    });
                    dialog.show();
                }
            }
        });

        //저장 버튼
        schedule_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                on_save = true;

                //api 통신으로 mqtt로 설정 전송 및 mysql에 데이터 저장
                save_schedule_data = new HashMap<>();
                save_schedule_data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                save_schedule_data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
                save_schedule_data.put("mc_idx", mc_idx);
                save_schedule_data.put("mac", mc_iot_mac);

                String start_day_list = "";
                String start_time_list = "";
                String end_day_list = "";
                String end_time_list = "";
                String schedule_data = "Z";

                for (int i = 0; i < relay_list.size(); i++) {
                    if (relay_list.get(i).getRsIdx() == null) {
                        add_list.add(relay_list.get(i));
                    }
                }

                if (add_list.size() == 1) {
                    schedule_data = "Y";
                    save_schedule_data.put("start_day_list", add_list.get(0).getRsStartDay());
                    save_schedule_data.put("start_time_list", add_list.get(0).getRsStartTime());
                    save_schedule_data.put("end_day_list", add_list.get(0).getRsEndDay());
                    save_schedule_data.put("end_time_list", add_list.get(0).getRsEndTime());

                } else if (add_list.size() > 1) {
                    for (int i = 0; i < add_list.size(); i++) {

                        if (i > 0) {
                            start_day_list = start_day_list + "," + add_list.get(i).getRsStartDay();
                            start_time_list = start_time_list + "," + add_list.get(i).getRsStartTime();
                            end_day_list = end_day_list + "," + add_list.get(i).getRsEndDay();
                            end_time_list = end_time_list + "," + add_list.get(i).getRsEndTime();

                        } else {
                            start_day_list = start_day_list + add_list.get(i).getRsStartDay();
                            start_time_list = start_time_list + add_list.get(i).getRsStartTime();
                            end_day_list = end_day_list + add_list.get(i).getRsEndDay();
                            end_time_list = end_time_list + add_list.get(i).getRsEndTime();
                        }
                    }
                    schedule_data = "N";
                    save_schedule_data.put("start_day_list", start_day_list);
                    save_schedule_data.put("start_time_list", start_time_list);
                    save_schedule_data.put("end_day_list", end_day_list);
                    save_schedule_data.put("end_time_list", end_time_list);
                }

                if (del_list.size() == 1) {
                    save_schedule_data.put("del_idx", del_list.get(0));

                } else if (del_list.size() > 1) {
                    String del_list_str = del_list.toString();
                    del_list_str = del_list_str.replace("[", "");
                    del_list_str = del_list_str.replace("]", "");
                    save_schedule_data.put("del_list", del_list_str);
                }

                Integer schedule[] = new Integer[]{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
//                Integer schedule[] = new Integer[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

                int cnt = 0;
                for (int k = 0; k < relay_list.size(); k++) {
                    switch (relay_list.get(k).getRsStartDay()) {
                        case "0":
                            int sun_data = convert_binary(relay_list.get(k).getRsStartDay(), relay_list.get(k).getRsStartTime(), relay_list.get(k).getRsEndDay(), relay_list.get(k).getRsEndTime());
                            schedule[cnt] = sun_data;
                            break;
                        case "1":
                            if (cnt < 5) cnt = 5;
                            int mon_data = convert_binary(relay_list.get(k).getRsStartDay(), relay_list.get(k).getRsStartTime(), relay_list.get(k).getRsEndDay(), relay_list.get(k).getRsEndTime());
                            schedule[cnt] = mon_data;
                            break;
                        case "2":
                            if (cnt < 10) cnt = 10;
                            int tue_data = convert_binary(relay_list.get(k).getRsStartDay(), relay_list.get(k).getRsStartTime(), relay_list.get(k).getRsEndDay(), relay_list.get(k).getRsEndTime());
                            schedule[cnt] = tue_data;
                            break;
                        case "3":
                            if (cnt < 15) cnt = 15;
                            int wen_data = convert_binary(relay_list.get(k).getRsStartDay(), relay_list.get(k).getRsStartTime(), relay_list.get(k).getRsEndDay(), relay_list.get(k).getRsEndTime());
                            schedule[cnt] = wen_data;
                            break;
                        case "4":
                            if (cnt < 20) cnt = 20;
                            int thu_data = convert_binary(relay_list.get(k).getRsStartDay(), relay_list.get(k).getRsStartTime(), relay_list.get(k).getRsEndDay(), relay_list.get(k).getRsEndTime());
                            schedule[cnt] = thu_data;
                            break;
                        case "5":
                            if (cnt < 25) cnt = 25;
                            int fri_data = convert_binary(relay_list.get(k).getRsStartDay(), relay_list.get(k).getRsStartTime(), relay_list.get(k).getRsEndDay(), relay_list.get(k).getRsEndTime());
                            schedule[cnt] = fri_data;
                            break;
                        case "6":
                            if (cnt < 30) cnt = 30;
                            int sat_data = convert_binary(relay_list.get(k).getRsStartDay(), relay_list.get(k).getRsStartTime(), relay_list.get(k).getRsEndDay(), relay_list.get(k).getRsEndTime());
                            schedule[cnt] = sat_data;
                            break;
                    }
                    cnt++;
                }

                String schedule_list = Arrays.toString(schedule);
                schedule_list = schedule_list.replace("[", "");
                schedule_list = schedule_list.replace("]", "");
                save_schedule_data.put("schedule_list", schedule_list);
                save_schedule_data.put("schedule_data", schedule_data);

                String schedule_save_datas =
                        Common.getInstance().convert_mqtt_value_int("mon_1", schedule[5]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("mon_2", schedule[6]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("mon_3", schedule[7]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("mon_4", schedule[8]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("mon_5", schedule[9]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("tue_1", schedule[10]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("tue_2", schedule[11]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("tue_3", schedule[12]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("tue_4", schedule[13]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("tue_5", schedule[14]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("wed_1", schedule[15]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("wed_2", schedule[16]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("wed_3", schedule[17]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("wed_4", schedule[18]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("wed_5", schedule[19]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("thu_1", schedule[20]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("thu_2", schedule[21]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("thu_3", schedule[22]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("thu_4", schedule[23]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("thu_5", schedule[24]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("fri_1", schedule[25]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("fri_2", schedule[26]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("fri_3", schedule[27]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("fri_4", schedule[28]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("fri_5", schedule[29]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("sat_1", schedule[30]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("sat_2", schedule[31]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("sat_3", schedule[32]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("sat_4", schedule[33]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("sat_5", schedule[34]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("sun_1", schedule[0]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("sun_2", schedule[1]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("sun_3", schedule[2]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("sun_4", schedule[3]) + ", " +
                                Common.getInstance().convert_mqtt_value_int("sun_5", schedule[4]);

                String msg = "{'opt' : 4, " + schedule_save_datas + "}";
                JsonParser get_parser = new JsonParser();
                Object obj = get_parser.parse(msg);

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

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

                progressDialog = new ProgressDialog(getContext());
                schedule_activeLL.setEnabled(false);
                progressDialog.setIndeterminate(true);
                progressDialog.setMessage("스케줄 등록 중입니다...");
                progressDialog.show();
                on_schedule_save = true;

                timer_thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                            if (fa != null) {
                                fa.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Common.getInstance().unSubscribeTopic("check/" + mc_iot_mac, schedule_mqttAndroidClient);
                                        Common.getInstance().toastShow(getContext(), "스케줄 등록에 실패했습니다.\nIoT 기기의 인터넷 연결을 확인해주세요.");
                                        progressDialog.dismiss();
                                    }
                                });
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                });

                timer_thread.start();
            }
        });

        //스케줄 추가 버튼
        schedule_addLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (relay_list.size() > 35) {
                    Toast.makeText(getContext(), "하루에 최대 다섯개의 스케줄 등록이 가능합니다.\n새로운 스케줄을 추가하려면 기존 스케줄을 삭제 후 진행해주세요.", Toast.LENGTH_SHORT).show();
                }

                AddScheduleDialog2 dialog = new AddScheduleDialog2(getContext(), handler, relay_list, new AddScheduleDialog2.clickListener() {
                    @Override
                    public void clickBtn(HashMap<String, String> data) {
                        RelayData relayData = new RelayData();
                        relayData.setRsStartDay(data.get("rs_start_day"));
                        relayData.setRsStartTime(data.get("rs_start_hour") + ":" + data.get("rs_start_min"));
                        relayData.setRsEndDay(data.get("rs_end_day"));
                        relayData.setRsEndTime(data.get("rs_end_hour") + ":" + data.get("rs_end_min"));
                        relayData.setRsMemo(data.get("rs_memo"));

                        relay_list.add(relayData);
                        Collections.sort(relay_list, cmpAsc);

                        adapter.addItems(relay_list);
                    }
                });
                dialog.show();
            }
        });
    }

    private int convert_binary(String s_day, String s_time, String e_day, String e_time) {
        int start_min = Integer.parseInt(s_time.substring(3, 5)) << 24;
        int start_day = Integer.parseInt(s_day) << 21;
        int start_time = Integer.parseInt(s_time.substring(0, 2)) << 16;

        int end_min = Integer.parseInt(e_time.substring(3, 5)) << 8;
        int end_day = Integer.parseInt(e_day) << 5;
        int end_time = Integer.parseInt(e_time.substring(0, 2));

        return start_day | start_time | start_min | end_day | end_time | end_min;
    }

    private 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_relay_schedule_save")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        relay_array = new Gson().fromJson(result_item, new TypeToken<ArrayItem<RelayData>>() {
                        }.getType());

                        edit_mode = false;
                        adapter = new RelayScheduleAdapter(getContext(), edit_mode, schedule_active);
                        relay_scheduleRV.setAdapter(adapter);

                        if (relay_array.isSuccess()) {
                            adapter.addItems(relay_array.getArrayitem());
                            relay_list.clear();
                            add_list.clear();
                            del_list.clear();

                            schedule_saveTV.setVisibility(View.GONE);
                            schedule_addLL.setVisibility(View.GONE);

                        } else {
                            get_relay_schedule();
                            schedule_activeLL.setVisibility(View.VISIBLE);
                            relay_list.clear();
                            add_list.clear();
                            del_list.clear();
                        }

                        progressDialog.dismiss();
                        schedule_mainTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_blue));
                        schedule_modeTV.setTextColor(Color.BLACK);
                        schedule_activeLL.setVisibility(View.VISIBLE);
                        schedule_activeLL.setEnabled(true);
                        schedule_editLL.setVisibility(View.VISIBLE);

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

                        if (relay_array.isSuccess()) {
                            adapter.addItems(relay_array.getArrayitem());

                        } else {
                            Common.getInstance().toastShow(getContext(), "등록된 스케줄이 없습니다. 스케줄을 등록해주세요.");
                        }

                        schedule_saveTV.setVisibility(View.GONE);
                        schedule_addLL.setVisibility(View.GONE);
                        schedule_mainTV.setTextColor(getContext().getResources().getColor(R.color.color_bg_blue));
                        schedule_modeTV.setTextColor(Color.BLACK);
                        schedule_activeLL.setVisibility(View.VISIBLE);

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

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

                            if (mc_schedule_yn.equals("Y")) {
                                schedule_activeIV.setImageResource(R.drawable.icon_power_green);
                                final Animation animation = new AlphaAnimation(1, 0);
                                animation.setDuration(1500);
                                animation.setInterpolator(new LinearInterpolator());
                                animation.setRepeatCount(Animation.INFINITE);
                                animation.setRepeatMode(Animation.RESTART);
                                schedule_activeIV.startAnimation(animation);
                                schedule_activeTV.setText("스케줄 운전");
                                schedule_active = true;

                            } else {
                                schedule_activeIV.setImageResource(R.drawable.icon_power_red);
                                schedule_activeIV.clearAnimation();
                                schedule_activeTV.setText("스케줄 정지");
                                schedule_active = false;
                            }

                            adapter = new RelayScheduleAdapter(getContext(), edit_mode, schedule_active);
                            relay_scheduleRV.setAdapter(adapter);
                            adapter.addItems(relay_array.getArrayitem());

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_LONG).show();
                        }
                        progressDialog.dismiss();
                        schedule_activeLL.setVisibility(View.VISIBLE);
                        schedule_activeLL.setEnabled(true);
                    }

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

    private static Comparator<RelayData> cmpAsc = new Comparator<RelayData>() {
        @Override
        public int compare(RelayData o1, RelayData o2) {
            if (o1.getRsStartDay().equals(o2.getRsStartDay())) {
                return o1.getRsStartTime().compareTo(o2.getRsStartTime());
            } else {
                return o1.getRsStartDay().compareTo(o2.getRsStartDay());
            }
        }
    };

    @Override
    public void onStop() {
        super.onStop();
        if (schedule_mqttAndroidClient != null && schedule_mqttAndroidClient.isConnected()) {
            schedule_mqttAndroidClient = Common.getInstance().mqtt_disconnect(schedule_mqttAndroidClient);
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        edit_mode = false;
        adapter = new RelayScheduleAdapter(getContext(), edit_mode, schedule_active);
        relay_scheduleRV.setAdapter(adapter);
        on_active = false;

        if (schedule_mqttAndroidClient == null)
            mqtt_connect();
        get_relay_schedule();

        schedule_activeLL.setVisibility(View.VISIBLE);
        schedule_activeLL.setEnabled(true);
        schedule_editLL.setVisibility(View.VISIBLE);

        relay_list.clear();
        add_list.clear();
        del_list.clear();
    }

    void mqtt_connect() {

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

        schedule_mqttAndroidClient.setCallback(new MqttCallback() {

            @Override
            public void connectionLost(Throwable cause) {
                Log.i("@@@", "스케줄 connectionLost");
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                JsonParser parser = new JsonParser();
                JsonObject jsonObject = (JsonObject) parser.parse(new String(message.getPayload()));

                MonitoringData monitoringData;
                monitoringData = new Gson().fromJson(jsonObject, new TypeToken<MonitoringData>() {
                }.getType());

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

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

                    if (monitoringData.getOpt6Cnt().equals("1") && on_active) {

                        HashMap<String, String> data = new HashMap<>();
                        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                        data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
                        data.put("mc_idx", mc_idx);
                        data.put("mac", mc_iot_mac);
                        data.put("mb_id", fa.userItem.getArrayitem().getMbId());
                        data.put("mc_schedule_yn", mc_schedule_yn);

                        Log.d("데이터 확인@@@@", data.toString());
                        new ApiClient(data, "proc_relay_schedule_onoff", handler);

                        on_active = false;
                        Common.getInstance().unSubscribeTopic("check/" + mc_iot_mac, schedule_mqttAndroidClient);

                    } else if (monitoringData.getOpt4Cnt().equals("1") && on_save) {
                        new ApiClient(save_schedule_data, "proc_relay_schedule_save", handler);
                        on_schedule_save = false;
                        on_save = false;
                    }
                }
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
            }
        });
    }
}