package kr.co.compcareworker.Fragment.Machine;

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.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
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 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.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Activity.MainActivity;
import kr.co.compcareworker.Data.ArrayItem_;
import kr.co.compcareworker.Data.Company.Machine.Product.MonitoringData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;

public class Add_Machine_Fragment3 extends Fragment {

    FragmentActivity fa;
    Handler handler, hdr;

    ImageView mac_refreshIV;
    TextView macTV, mac_noticeTV, pd_nameTV, pd_specTV, add_machineTV, esr_noticeTV;
    Button esr20Btn, esr30Btn, esr50Btn;
    String cp_idx, pt_idx, qr, mc_type;
    LinearLayout pd_infoLL;

    @SuppressLint("ValidFragment")
    public Add_Machine_Fragment3(Handler handler, String cp_idx, String pt_idx, String qr) {
        this.handler = handler;
        this.cp_idx = cp_idx;
        this.pt_idx = pt_idx;
        this.qr = qr;
    }

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

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

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.frag_add_machine3, container, false);

        macTV = v.findViewById(R.id.macTV);
        mac_refreshIV = v.findViewById(R.id.mac_refreshIV);
        mac_noticeTV = v.findViewById(R.id.mac_noticeTV);
        esr20Btn = v.findViewById(R.id.esr20Btn);
        esr30Btn = v.findViewById(R.id.esr30Btn);
        esr50Btn = v.findViewById(R.id.esr50Btn);
        pd_nameTV = v.findViewById(R.id.pd_nameTV);
        pd_specTV = v.findViewById(R.id.pd_specTV);
        add_machineTV = v.findViewById(R.id.add_machineTV);
        esr_noticeTV = v.findViewById(R.id.esr_noticeTV);
        pd_infoLL = v.findViewById(R.id.pd_infoLL);

        init_Handler();
        init_Listener();
        Get_Mac();

        return v;
    }

    void Get_Mac() {
        HashMap<String, String> get_data = new HashMap<>();
        get_data.put("qr_code", qr.replace("Q", ""));
        new ApiClient(get_data, "proc_influx_mac_get", 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();
                        ArrayItem_<MonitoringData> mac_items = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<MonitoringData>>() {
                        }.getType());

                        if (mac_items.isSuccess()) {
                            macTV.setText(mac_items.getArrayitem().getMAC());
                            mac_noticeTV.setText("※ 가져온 MAC 주소와 기계의 MAC 주소가 일치하는지 확인하세요! ※");
                            mac_noticeTV.setTextColor(getContext().getResources().getColor(R.color.green));

                        } else {
                            macTV.setText("");
                            mac_refreshIV.setVisibility(View.VISIBLE);
                            mac_noticeTV.setText("※ 새로고침해서 다시 시도해주세요 ※");
                            mac_noticeTV.setTextColor(getContext().getResources().getColor(R.color.red));
                            Toast.makeText(getContext(), "등록 가능한 MAC이 없습니다", Toast.LENGTH_SHORT).show();
                        }

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

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Common.getInstance().toastShow(getContext(), "QR 코드와 머신을 등록했습니다");
                            Intent intent = new Intent(getContext(), MainActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);

                        } else {
                            Common.getInstance().toastShow(getContext(), "등록에 실패했습니다.");
                        }

                    }

                } else if (msg.what == -1) {
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                }
            }
        };
    }

    void init_Listener() {

        //20마력
        esr20Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pd_infoLL.setVisibility(View.VISIBLE);
                pd_nameTV.setText("ESR-20");
                pd_specTV.setText("8K 380V(삼상) 60HZ");
                mc_type = "ESR20";
                esr20Btn.setBackgroundResource(R.drawable.bg_round_dark_yellow_30);
                esr30Btn.setBackgroundResource(R.drawable.bg_round_gray_30);
                esr50Btn.setBackgroundResource(R.drawable.bg_round_gray_30);

                if (!TextUtils.isEmpty(macTV.getText().toString())) {
                    add_machineTV.setEnabled(true);
                    add_machineTV.setBackgroundResource(R.drawable.bg_round_main_30);
                }
            }
        });

        //30마력
        esr30Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pd_infoLL.setVisibility(View.VISIBLE);
                pd_nameTV.setText("ESR-30");
                pd_specTV.setText("8K 380V(삼상) 60HZ");
                mc_type = "ESR30";
                esr20Btn.setBackgroundResource(R.drawable.bg_round_gray_30);
                esr30Btn.setBackgroundResource(R.drawable.bg_round_dark_yellow_30);
                esr50Btn.setBackgroundResource(R.drawable.bg_round_gray_30);

                if (!TextUtils.isEmpty(macTV.getText().toString())) {
                    add_machineTV.setEnabled(true);
                    add_machineTV.setBackgroundResource(R.drawable.bg_round_main_30);
                }
            }
        });

        //50마력
        esr50Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pd_infoLL.setVisibility(View.VISIBLE);
                pd_nameTV.setText("ESR-50");
                pd_specTV.setText("8K 380V(삼상) 60HZ");
                mc_type = "ESR50";
                esr20Btn.setBackgroundResource(R.drawable.bg_round_gray_30);
                esr30Btn.setBackgroundResource(R.drawable.bg_round_gray_30);
                esr50Btn.setBackgroundResource(R.drawable.bg_round_dark_yellow_30);

                if (!TextUtils.isEmpty(macTV.getText().toString())) {
                    add_machineTV.setEnabled(true);
                    add_machineTV.setBackgroundResource(R.drawable.bg_round_main_30);
                }
            }
        });

        //저장
        add_machineTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(macTV.getText().toString())) {
                    Common.getInstance().toastShow(getContext(), "MAC 주소를 검색해주세요");
                    return;
                }

                if (TextUtils.isEmpty(mc_type)) {
                    Common.getInstance().toastShow(getContext(), "등록하려는 모델을 선택해주세요");
                    return;
                }
                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", fa.enterpriseItem.getArrayitem().getAgIdx());
                data.put("pt_idx", pt_idx);
                data.put("cp_idx", cp_idx);
                data.put("mc_type", mc_type);
                data.put("mc_iot_mac", macTV.getText().toString());
                data.put("qr_code", qr);

                Log.d("데이터확인@@@@2", data.toString());
                new ApiClient(data, "proc_add_machine3", hdr);
            }
        });

    }


}

