package kr.co.compcarecompany.Util.CustomView;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

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.Data.ArrayItem;
import kr.co.compcarecompany.Data.ArrayItem_;
import kr.co.compcarecompany.Data.Product.MonitoringData;
import kr.co.compcarecompany.MyApplication;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;

public class AddIotDialog extends Dialog {

    Context context;
    private String qr_code, ag_idx, pt_idx, cp_idx, mc_idx, mc_airline, mac;
    private Handler hdr;
    private Spinner dlg_iot_macSN;
    private TextView dlg_iot_saveTV, dlg_iot_qrTV;
    private EditText dlg_iot_running_timeET, dlg_iot_remain_timeET;
    private ArrayAdapter<String> iot_adapter;
    private MonitoringData monitoringData;

    private Thread timer_thread;
    private MqttAndroidClient iot_mqttAndroidClient;

    private AddIotDialog.clickListener clickListener;
    private boolean mac_is_correct = true;

    public interface clickListener {
        void clickBtn(String mac);
    }

    public AddIotDialog(@NonNull Context context, Handler hdr, String ag_idx, String pt_idx, String cp_idx, String mc_idx, String mc_airline, String qr_code, AddIotDialog.clickListener clickListener) {
        super(context);
        this.context = context;
        this.hdr = hdr;
        this.ag_idx = ag_idx;
        this.pt_idx = pt_idx;
        this.cp_idx = cp_idx;
        this.mc_idx = mc_idx;
        this.mc_airline = mc_airline;
        this.qr_code = qr_code;
        this.clickListener = clickListener;
    }

    public AddIotDialog(@NonNull Context context, Handler hdr, String ag_idx, String pt_idx, String cp_idx, String mc_idx, String mc_airline) {
        super(context);
        this.context = context;
        this.hdr = hdr;
        this.ag_idx = ag_idx;
        this.pt_idx = pt_idx;
        this.cp_idx = cp_idx;
        this.mc_idx = mc_idx;
        this.mc_airline = mc_airline;
        this.qr_code = "NO QR CODE";
    }

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setContentView(R.layout.dlg_add_iot);

        Display display = getWindow().getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        Window thisWindow = this.getWindow();

        int x = (int) (size.x * 0.95f);
        int y = (int) (size.y * 0.90f);

        thisWindow.setLayout(x, y);

        dlg_iot_saveTV = findViewById(R.id.dlg_iot_saveTV);
        dlg_iot_macSN = findViewById(R.id.dlg_iot_macSN);
        dlg_iot_qrTV = findViewById(R.id.dlg_iot_qrTV);
        dlg_iot_running_timeET = findViewById(R.id.dlg_iot_running_timeET);
        dlg_iot_remain_timeET = findViewById(R.id.dlg_iot_remain_timeET);

        //21.10.20 MAC 주소 검색색
//        search_macRL = findViewById(R.id.search_macRL);
//        search_macET = findViewById(R.id.search_macET);
//        search_macIV = findViewById(R.id.search_macIV);

        dlg_iot_qrTV.setText(qr_code);

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

        Get_Mac();
    }

    void Get_Mac() {
        HashMap<String, String> get_data = new HashMap<>();
        if (!qr_code.contains("No")) {
            get_data.put("qr_code", qr_code.replace("Q", ""));
        }
        new ApiClient(get_data, "proc_influx_mac_get", hdr);
    }

    void init_Listener() {

        dlg_iot_macSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mac = dlg_iot_macSN.getSelectedItem().toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        dlg_iot_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String mc_runningtime_total = dlg_iot_running_timeET.getText().toString();
                String mc_cycle = dlg_iot_remain_timeET.getText().toString();

                if (TextUtils.isEmpty(mc_runningtime_total) || TextUtils.isEmpty(mc_cycle)) {
                    Common.getInstance().toastShow(getContext(), "전체 항목을 입력해주세요.");
                    return;
                }

                if (!mac_is_correct || TextUtils.isEmpty(mac)) {
                    Common.getInstance().toastShow(getContext(), "MAC 주소를 확인 해주세요.");
                    return;
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", ag_idx);
                data.put("pt_idx", pt_idx);
                data.put("cp_idx", cp_idx);
                data.put("mc_idx", mc_idx);
                data.put("mc_airline", mc_airline);
                data.put("mc_iot_mac", mac);
                data.put("qr_code", qr_code);
                data.put("mc_runningtime_total", mc_runningtime_total);
                data.put("mc_cycle", mc_cycle);
                Log.d("데이터확인@@@@", data.toString());
                new ApiClient(data, "proc_machine_update", hdr);
            }
        });

        //mac주소 검색 21.10.20
//        search_macIV.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                HashMap<String, String> data = new HashMap<>();
//                data.put("mac", search_macET.getText().toString());
//                new ApiClient(data, "proc_search_mac", hdr);
//            }
//        });
    }


    void init_Handler() {

        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String url = msg.getData().getString("url");

                if (msg.what == 1) {

                    if (url.equals("proc_influx_mac_get")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        iot_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);

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

                            if (result_item.get("resultItem").getAsJsonObject().get("message").getAsString().equals("1")) {
                                ArrayItem_<MonitoringData> mac_items = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<MonitoringData>>() {
                                }.getType());
                                iot_adapter.add(mac_items.getArrayitem().getMAC());
                                dlg_iot_macSN.setAdapter(iot_adapter);

                            } else {

                                ArrayItem<MonitoringData> mac_items = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MonitoringData>>() {
                                }.getType());

                                for (int i = 0; i < mac_items.size(); i++) {
                                    String str = mac_items.getArrayitem().get(i).getMAC();
                                    iot_adapter.add(str);
                                }
                                dlg_iot_macSN.setAdapter(iot_adapter);
                            }

                        } else {
                            Toast.makeText(getContext(), "등록 가능한 MAC이 없습니다.", Toast.LENGTH_SHORT).show();
                            dismiss();
                        }

                    } else if (url.equals("proc_machine_update")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        Log.d("모냥@@@@", result_item.toString());

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            if (!qr_code.contains("QR CODE")) clickListener.clickBtn(mac);
                            dismiss();

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

                        //MAC  주소 검색 21.10.20
                    }

//                    else if (url.equals("proc_search_mac")) {
//                        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(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
//                            mac = search_macET.getText().toString();
//                            search_macRL.setBackgroundResource(R.drawable.border_green_fill_white);
//                            mac_is_correct = true;
//
//                        } else {
//                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
//                            mac = null;
//                            mac_is_correct = false;
//                            search_macRL.setBackgroundResource(R.drawable.border_red);
//                        }
//
//                    }

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


    void mqtt_connect() {

        if (iot_mqttAndroidClient == null) {
            iot_mqttAndroidClient = Common.getInstance().mqtt_connect(context, iot_mqttAndroidClient);
        }

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

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

                Log.d("확인이요@@@@", message.toString() + " //topic : " + topic);

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

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

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

                    Common.getInstance().unSubscribeTopic(topic, iot_mqttAndroidClient);

                    if (monitoringData != null && monitoringData.getMAC() != null) {

                        iot_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);
                        String str = monitoringData.getMAC();
                        iot_adapter.add(str);
                        dlg_iot_macSN.setAdapter(iot_adapter);

                        String msg = "{'opt9_cnt' : 0}";
                        JsonParser send_parser = new JsonParser();
                        Object obj = send_parser.parse(msg);
                        Common.getInstance().publishMessage("check/" + monitoringData.getMAC(), obj.toString(), iot_mqttAndroidClient);

                    }
                }
            }

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


