package kr.co.compcareworker.Fragment.Machine;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
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.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
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 androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
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 gun0912.tedimagepicker.builder.TedImagePicker;
import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.Company.Machine.MachineItem;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.PlanImageRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;

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

    FragmentActivity fa;
    Handler handler, hdr;

    ImageView machine_qrIV, machine_photoIV;
    TextView machine_qrTV, machine_delTV, machine_backTV, machine_nextTV, machine_typeTV;
    Spinner machine_typeSP, machine_productSP;
    LinearLayout machine_addPhotoLL, machine_type_noneLL, machine_type_existLL;
    RelativeLayout machine_photoRL;
    String cp_idx, pt_idx, qr, airline, airline_array, machine_type, product, mc_idx, pd_idx;
    ArrayAdapter<String> machine_type_adapter, machine_product_adapter;
    ArrayItem<MachineItem> items;
    MachineItem item;
    ArrayList<String> arr = new ArrayList<>();
    ArrayList<Uri> imageUriArray;
    PlanImageRecyclerAdapter photo_adapter;
    RecyclerView machine_photoRV;
    GridLayoutManager layoutManager;

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

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

        machine_qrIV = v.findViewById(R.id.machine_qrIV);
        machine_qrTV = v.findViewById(R.id.machine_qrTV);
        machine_typeSP = v.findViewById(R.id.machine_typeSP);
        machine_productSP = v.findViewById(R.id.machine_productSP);
        machine_addPhotoLL = v.findViewById(R.id.machine_addPhotoLL);
        machine_photoRL = v.findViewById(R.id.machine_photoRL);
        machine_photoIV = v.findViewById(R.id.machine_photoIV);
        machine_delTV = v.findViewById(R.id.machine_delTV);
        machine_backTV = v.findViewById(R.id.machine_backTV);
        machine_nextTV = v.findViewById(R.id.machine_nextTV);
        machine_photoRV = v.findViewById(R.id.machine_photoRV);
        machine_type_noneLL = v.findViewById(R.id.machine_type_noneLL);
        machine_type_existLL = v.findViewById(R.id.machine_type_existLL);
        machine_typeTV = v.findViewById(R.id.machine_typeTV);

        int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3f, getResources().getDisplayMetrics());
        int itemHeight = (Common.getInstance().getWidth(getActivity()));
        photo_adapter = new PlanImageRecyclerAdapter(getActivity(), itemHeight);
        layoutManager = new GridLayoutManager(getContext(), 5);
        machine_photoRV.setLayoutManager(layoutManager);
        machine_photoRV.setAdapter(photo_adapter);

        init_Handler();
        Get_Machine_list();
        init_Listener();

        return v;
    }

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

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

                        if (items.isSuccess()) {

                            //기종선택 스피너
                            for (int i = 0; i < items.size(); i++) {
                                item = items.getArrayitem().get(i);
                                String str = item.getPdName();
                                machine_product_adapter.add(str);
                            }

                            machine_type_existLL.setVisibility(View.VISIBLE);

                        } else {

                            machine_product_adapter.add("등록된 기종 없음(기종추가)");
                            machine_type_noneLL.setVisibility(View.VISIBLE);
                            Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_SHORT).show();
                        }

                        machine_productSP.setAdapter(machine_product_adapter);
                        Set_Contents();
                    }
                } else if (msg.what == -1) {

                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                }
            }
        };
    }

    //회사에 등록된 기계 목록 불러오기
    void Get_Machine_list() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("cp_idx", cp_idx);
        new ApiClient(data, "proc_machine_list", hdr);
    }

    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);
            machine_qrIV.setImageBitmap(bitmap);
        } catch (Exception e) {
        }

        machine_qrTV.setText(qr);

        //제품구분 스피너
        String[] machine_array = {"Compressor", "Tank", "After Cooler", "Dryer", "Filter", "흡착식", "OIL MIST SEPERATOR", "AUTO TRAP"};

        machine_type_adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, machine_array);
        machine_typeSP.setAdapter(machine_type_adapter);
    }

    void init_Listener() {

        //선택한 제품구분
        machine_typeSP.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                machine_type = machine_typeSP.getSelectedItem().toString();

                if ("Compressor".equals(machine_type) || "COMP".equals(machine_type)) {

                    machine_type = "COMP";
                } else if ("Tank".equals(machine_type) || "TANK".equals(machine_type)) {

                    machine_type = "TANK";
                } else if ("After Cooler".equals(machine_type) || "COOLER".equals(machine_type)) {

                    machine_type = "COOLER";
                } else if ("Dryer".equals(machine_type) || "DRYER".equals(machine_type)) {

                    machine_type = "DRYER";
                } else if ("Filter".equals(machine_type) || "FILTER".equals(machine_type)) {

                    machine_type = "FILTER";
                } else {

                    machine_type = "ETC";
                }
            }

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

            }
        });

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

                if (items.isSuccess()) {

                    product = machine_productSP.getSelectedItem().toString();
                    mc_idx = items.getArrayitem().get(position).getMcIdx();
                    machine_typeTV.setText(items.getArrayitem().get(position).getMcTtype());
                    machine_type = machine_typeTV.getText().toString();
                    pd_idx = items.getArrayitem().get(position).getPdIdx();

                    if (TextUtils.isEmpty(machine_type)) {

                        machine_type_existLL.setVisibility(View.GONE);
                        machine_type_noneLL.setVisibility(View.VISIBLE);

                    } else {

                        machine_type_existLL.setVisibility(View.VISIBLE);
                        machine_type_noneLL.setVisibility(View.GONE);
                    }

                } else {

                    product = "QR을 통해 기종추가 됨";
                    mc_idx = null;
                    pd_idx = null;
                }
            }

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

            }
        });

        machine_addPhotoLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectSize = photo_adapter.getItemCount();
                if (selectSize < 5) {
                    TedImagePicker.with(requireContext())
                            .startMultiImage(uriList -> {
                                for (int i = 0; i < uriList.size(); i++) {
                                    arr.add(uriList.get(i).toString());
                                }

                                photo_adapter.addItem(arr);
                                machine_photoRV.setAdapter(photo_adapter);
                            });

//                    TedBottomPicker tedBottomPicker = new TedBottomPicker.Builder(getContext()).setImageProvider(new TedBottomPicker.ImageProvider() {
//                        @Override
//                        public void onProvideImage(ImageView imageView, Uri imageUri) {
//                            Glide.with(getContext()).load(imageUri).apply(RequestOptions.centerCropTransform()).into(imageView);
//                        }
//                    }).setOnMultiImageSelectedListener(new TedBottomPicker.OnMultiImageSelectedListener() {
//                        @Override
//                        public void onImagesSelected(ArrayList<Uri> uriList) {
//
//                            for (int i = 0; i < uriList.size(); i++) {
//                                arr.add(uriList.get(i).toString());
//                            }
//
//                            photo_adapter.addItem(arr);
//                            machine_photoRV.setAdapter(photo_adapter);
//
//                        }
//                    })
//                            .setCompleteButtonText("저장")
//                            .setPeekHeight(2400)
//                            .setPreviewMaxCount(1000).setSelectMaxCount(5 - selectSize).create();
//                    tedBottomPicker.show(getActivity().getSupportFragmentManager());

                } else {
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("사진은 최대 5장까지 등록가능합니다.");
                    dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.show();
                }
            }
        });

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

        //다음
        machine_nextTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "머신 등록");
                intent.putExtra("type", "add_iot");
                intent.putExtra("value1", cp_idx);
                intent.putExtra("value2", pt_idx);
                intent.putExtra("value3", qr);
                intent.putExtra("value4", airline);
                intent.putExtra("value5", airline_array);
                intent.putExtra("value6", machine_type);
                intent.putExtra("value7", mc_idx);
                intent.putExtra("value8", arr);

                startActivity(intent);
            }
        });
    }
}
