package kr.co.compcareworker.Fragment.Machine.ProdQR;

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.webkit.WebView;
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.RecyclerView;

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.integration.android.IntentResult;

import java.util.HashMap;

import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Activity.QRCodeActivity;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.ArrayItem_;
import kr.co.compcareworker.Data.Company.CompanyData;
import kr.co.compcareworker.Data.Company.Machine.MachineItem;
import kr.co.compcareworker.Fragment.FragmentIntentIntegrator;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.ProdQRListRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;

@SuppressLint("ValidFragment")
public class ProdQR_Fragment extends Fragment {
    private Handler handler, hdr;

    FragmentActivity fa;

    String cp_idx, line_name, pt_idx;

    TextView name, office, line, addr, time, noneList;
    RecyclerView list;
    ProdQRListRecyclerAdapter adapter;

    ArrayItem_<CompanyData> item;

    ArrayItem<MachineItem> machine;

    WebView webView;

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

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

    @SuppressLint("ValidFragment")
    public ProdQR_Fragment(Handler handler, String cp_idx, String line_name) {
        this.handler = handler;
        this.cp_idx = cp_idx;
        this.line_name = line_name;
    }

    @SuppressLint("ValidFragment")
    public ProdQR_Fragment(String cp_idx, String pt_idx) {
        this.cp_idx = cp_idx;
        this.pt_idx = pt_idx;
    }

    @SuppressLint("ValidFragment")
    public ProdQR_Fragment(Handler handler) {
        this.handler = handler;
    }

    public ProdQR_Fragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_prod_qr_list, container, false);

        name = v.findViewById(R.id.name);
        office = v.findViewById(R.id.office);
        line = v.findViewById(R.id.line);
        addr = v.findViewById(R.id.addr);
        time = v.findViewById(R.id.time);
        list = v.findViewById(R.id.list);
        noneList = v.findViewById(R.id.noneList);
//        webView = v.findViewById(R.id.webView);

        //webView.setVisibility(View.GONE);

        init_Handler();
        init_Listener();

        adapter = new ProdQRListRecyclerAdapter(getContext(), hdr);
        list.setAdapter(adapter);

        if (TextUtils.isEmpty(cp_idx)) {

            Set_Contents();

        } else {
            Get_Contents();
        }

        return v;
    }

    void Get_Contents() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("cp_idx", cp_idx);
        new ApiClient(data, "proc_company_view", hdr);
    }

    void Set_Contents() {

        FragmentIntentIntegrator integrator = new FragmentIntentIntegrator(ProdQR_Fragment.this);
        integrator.setCaptureActivity(QRCodeActivity.class);
        integrator.setBarcodeImageEnabled(true);
        integrator.setOrientationLocked(false);
        integrator.initiateScan();
    }

    void init_Handler() {
        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

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

                } else if (msg.what == 1) {
                    String url = msg.getData().getString("url");

                    if (url != null) {
                        if (url.equals("proc_company_view")) {

                            JsonElement element = new JsonParser().parse(msg.obj.toString());
                            JsonObject result_item = element.getAsJsonObject();
                            item = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<CompanyData>>() {
                            }.getType());

                            if (item.isSuccess()) {
                                Set_Contents();

                            } else {
                                Toast.makeText(getContext(), item.getMessage(), Toast.LENGTH_SHORT).show();
                                getActivity().finish();
                            }

                        } else if (url.equals("proc_qr_code_edit")) {

                            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();
                                Get_Contents();

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

                            JsonElement element = new JsonParser().parse(msg.obj.toString());
                            JsonObject result_item = element.getAsJsonObject();
                            machine = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MachineItem>>() {
                            }.getType());

                            if (machine.isSuccess()) {

                                Toast.makeText(getContext(), "QR코드에 등록된 업체로 연결됩니다.", Toast.LENGTH_SHORT).show();
                                cp_idx = machine.getArrayitem().get(0).getCpIdx();
                                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(), "해당 QR코드에 등록된 업체가 없습니다.", Toast.LENGTH_SHORT).show();
                            }
                        }
                    } else {

                        FragmentIntentIntegrator integrator = new FragmentIntentIntegrator(ProdQR_Fragment.this);
                        integrator.setCaptureActivity(QRCodeActivity.class);
                        integrator.setBarcodeImageEnabled(true);
                        integrator.setOrientationLocked(false);
                        integrator.initiateScan();
                    }
                }
            }
        };
    }

    private void init_Listener() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        IntentResult result = FragmentIntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result.getContents() != null && !result.getContents().equals("")) {

            if (TextUtils.isEmpty(cp_idx)) {

                HashMap<String, String> get_data = new HashMap<>();
                get_data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                get_data.put("qr", result.getContents());
                new ApiClient(get_data, "proc_get_company_with_qr", hdr);

            } else if (!TextUtils.isEmpty(cp_idx) && !TextUtils.isEmpty(pt_idx)){
//                Intent intent = new Intent(getContext(), FragmentActivity.class);
//                intent.putExtra("title", "머신 등록");
//                intent.putExtra("type", "add_machine3");
//                intent.putExtra("value1", cp_idx);
//                intent.putExtra("value2", pt_idx);
//                intent.putExtra("value3", result.getContents());
//                startActivity(intent);
//                getActivity().finish();

            } else {
                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "머신 등록");
                intent.putExtra("type", "add_airline");
                intent.putExtra("value1", cp_idx);
                intent.putExtra("value2", item.getArrayitem().getPtIdx());
                intent.putExtra("value3", result.getContents());
                startActivity(intent);
                getActivity().finish();

            }

        } else {
            Toast.makeText(getContext(), "qr코드가 정상적으로 인식되지 않았습니다.", Toast.LENGTH_LONG).show();
            getActivity().finish();
        }
    }
}
