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.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.ProgressBar;
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 java.util.HashMap;

import kr.co.compcarecompany.Data.ArrayItem;
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;

public class MaxSettingDialog extends Dialog {

    Context context;
    private String mac, sensor, max;
    private Handler hdr;
    private Spinner dlg_max_sensorSN;
    private TextView dlg_max_saveTV, dlg_max_now_valueTV;
    private EditText dlg_max_valueET;
    private String[] sensor_array;
    private ArrayAdapter<String> sensor_adapter;
    private ProgressBar dlg_maxPB;
    private ArrayItem<MonitoringData> monitoring_item;

    public MaxSettingDialog(@NonNull Context context, Handler hdr, String mac) {
        super(context);
        this.context = context;
        this.hdr = hdr;
        this.mac = mac;
    }

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

        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_max_sensorSN = findViewById(R.id.dlg_max_sensorSN);
        dlg_max_valueET = findViewById(R.id.dlg_max_valueET);
        dlg_max_saveTV = findViewById(R.id.dlg_max_saveTV);
        dlg_maxPB = findViewById(R.id.dlg_maxPB);
        dlg_max_now_valueTV = findViewById(R.id.dlg_max_now_valueTV);

        //에어라인 스피너 초기화
        sensor_adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item);
        sensor_adapter.add("전류_1");
//        sensor_adapter.add("온도NTC");
//        sensor_adapter.add("압력_1");
//        for (String s : sensor_array) {
//            sensor_adapter.add(s);
//        }
        dlg_max_sensorSN.setAdapter(sensor_adapter);

        init_Handler();
        init_Listener();
        Get_Max();
    }

    void Get_Max() {
        HashMap<String, String> data = new HashMap<>();
        data.put("mac", mac);
        Log.d("데이터확인@@@@", data.toString());

        new ApiClient(data, "proc_admin_get_max", hdr);
    }

    void init_Listener() {

        //선택한 Air_Line
        dlg_max_sensorSN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                sensor = dlg_max_sensorSN.getSelectedItem().toString();
            }

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

            }
        });

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

                if (dlg_maxPB.getVisibility() == View.VISIBLE) {
                    return;
                }

                if (dlg_max_valueET.getText().toString().equals("")) {
                    Common.getInstance().toastShow(getContext(), "설정할 MAX 값을 입력하세요.");
                    return;
                }

                dlg_maxPB.setVisibility(View.VISIBLE);
                max = dlg_max_valueET.getText().toString();
//                String msg = "{'MAC':'"+mac+"', 'opt':3, 'max_setting':'>CURRENT1_MAX, "+max+"'}";
//                JsonParser parser = new JsonParser();
//                Object obj = parser.parse(msg);
//                Log.d("보자@@@@", obj.toString());
//
//                Common.getInstance().publishMessage(MyApplication.mqttAndroidClient, "control/"+mac, obj.toString());
//
//                MyApplication.mqttAndroidClient.setCallback(new MqttCallback() {
//                    @Override
//                    public void connectionLost(Throwable cause) {
//                        Log.i("@@@", "connection lost");
//                    }
//
//                    @Override
//                    public void messageArrived(String topic, MqttMessage message) throws Exception {
//                        Log.i("@@@", "topic: " + topic + ", msg: " + new String(message.getPayload()));
//                    }
//
//                    @Override
//                    public void deliveryComplete(IMqttDeliveryToken token) {
//                        Common.getInstance().toastShow(getContext(), "설정이 완료되었습니다.");
//                        Common.getInstance().subscribeTopic(MyApplication.mqttAndroidClient, "sensors/"+mac);
//                        dismiss();
//                    }
//                });

                HashMap<String, String> data = new HashMap<>();
                data.put("mac", mac);
                data.put("sensor", sensor);
                data.put("max", max);

                new ApiClient(data, "proc_admin_max_setting", 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_admin_max_setting")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    dlg_maxPB.setVisibility(View.GONE);
                                    Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                                    dismiss();
                                }
                            }, 3000);

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            dismiss();
                        }
                    } else if (url.equals("proc_admin_get_max")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        monitoring_item = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MonitoringData>>() {
                        }.getType());

                        if(monitoring_item.isSuccess()){
                            dlg_max_now_valueTV.setText(monitoring_item.getArrayitem().get(0).getCurrent1Max());
                        }
//                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
//
//                        } else {
//                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
//                        }
                    }

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


