package kr.co.compcareworker.Fragment.Machine;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
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 com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeEncoder;

import java.util.ArrayList;
import java.util.HashMap;

import kr.co.compcareworker.Activity.FragmentActivity;
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;

@SuppressLint("ValidFragment")
public class Add_Iot_Fragment extends Fragment {

    FragmentActivity fa;
    Handler handler, hdr;
    String cp_idx, pt_idx, qr, airline, airline_array, machine_type, mc_idx, mac;

    ImageView iot_qrIV;
    TextView iot_qrTV, iot_backTV, iot_nextTV;
    Spinner iot_macSP;
    ArrayList<String> photo;
    ArrayAdapter<String> iot_adapter;
    ArrayItem<MonitoringData> items;
    MonitoringData item;
    EditText iot_remain_timeET, iot_total_timeET;

    @SuppressLint("ValidFragment")
    public Add_Iot_Fragment(Handler handler, String cp_idx, String pt_idx, String qr, String airline, String airline_array, String machine_type, String mc_idx, ArrayList<String> photo) {
        this.handler = handler;
        this.cp_idx = cp_idx;
        this.pt_idx = pt_idx;
        this.qr = qr;
        this.airline = airline;
        this.airline_array = airline_array;
        this.machine_type = machine_type;
        this.mc_idx = mc_idx;
        this.photo = photo;
    }

    @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_iot, container, false);

        iot_qrIV = v.findViewById(R.id.iot_qrIV);
        iot_qrTV = v.findViewById(R.id.iot_qrTV);
        iot_backTV = v.findViewById(R.id.iot_backTV);
        iot_nextTV = v.findViewById(R.id.iot_nextTV);
        iot_macSP = v.findViewById(R.id.iot_macSP);
        iot_total_timeET = v.findViewById(R.id.iot_total_timeET);
        iot_remain_timeET = v.findViewById(R.id.iot_remain_timeET);

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

        return v;
    }

    void Set_Contents() {

        //qr 코드를 이용해서 qr 이미지 생성
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            BitMatrix bitMatrix = multiFormatWriter.encode(qr, BarcodeFormat.QR_CODE, 300, 300);
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
            iot_qrIV.setImageBitmap(bitmap);
        } catch (Exception e) {
        }

        iot_qrTV.setText(qr);

        if (!airline_array.contains(airline)) {

            airline_array = airline_array + "," + airline;
        }

    }

    void init_Listener() {

        iot_macSP.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                mac = iot_macSP.getSelectedItem().toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                mac = null;
            }
        });

        //취소
        iot_backTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

        //완료
        iot_nextTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String total_time = iot_total_timeET.getText().toString();
                String remain_time = iot_remain_timeET.getText().toString();

                if (TextUtils.isEmpty(total_time) || TextUtils.isEmpty(remain_time)) {
                    Toast.makeText(getContext(), "시간 설정을 입력해주세요.", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(mac)) {
                    Toast.makeText(getContext(), "MAC을 선택해주세요.", Toast.LENGTH_SHORT).show();
                    return;
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                data.put("cp_idx", cp_idx);
                data.put("pt_idx", pt_idx);
                data.put("qr", qr);
                data.put("airline", airline);
                data.put("airline_array", airline_array);
                data.put("machine_type", machine_type);
                data.put("mb_id", fa.userItem.getArrayitem().getMbId());
                data.put("mac", mac);
                data.put("mc_runningtime_total", total_time);
                data.put("mc_rest_time", remain_time);

                if (!TextUtils.isEmpty(mc_idx)) {

                    data.put("mc_idx", mc_idx);
                }

                ArrayList<Uri> photo_uri = new ArrayList<>();

                for (int i = 0; i < photo.size(); i++) {

                    photo_uri.add(Uri.parse(photo.get(i)));
                }

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

    void Get_Mac() {
        HashMap<String, String> data = new HashMap<>();
        new ApiClient(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_machine_registration")) {
                        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(), "성공했습니다.", Toast.LENGTH_SHORT).show();

                            Intent intent = new Intent(getContext(), FragmentActivity.class);
                            intent.putExtra("title", "설치장소 정보");
                            intent.putExtra("type", "enterprise");
                            intent.putExtra("value1", cp_idx);
                            startActivity(intent);
                            getActivity().finish();

                        } else {
                            Toast.makeText(getContext(), "등록 실패했습니다.", Toast.LENGTH_SHORT).show();
                        }
                    } else if (url.equals("proc_influx_mac_get")) {

                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        Log.d("확인@@@@", result_item.toString());
                        items = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MonitoringData>>() {
                        }.getType());

                        iot_adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item);

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

                            for (int i = 0; i < items.size(); i++) {
                                item = items.getArrayitem().get(i);
                                String str = item.getMac();
                                iot_adapter.add(str);
                                iot_macSP.setAdapter(iot_adapter);
                            }

                        } else {

                            Toast.makeText(getContext(), "등록된 MAC주소가 없습니다.", Toast.LENGTH_SHORT).show();
                        }

                    }
                } else if (msg.what == -1) {

                    Log.d("뭔뎅~~~@@@@", msg.toString());
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                }
            }
        };
    }
}
