package kr.co.compcarecompany.Util.Adapter;

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.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

import kr.co.compcarecompany.Activity.MainActivity;
import kr.co.compcarecompany.Activity.WebviewAct;
import kr.co.compcarecompany.Data.Company.CompanyData;
import kr.co.compcarecompany.Data.Product.AlMachineDatum;
import kr.co.compcarecompany.Data.Product.MachineItem;
import kr.co.compcarecompany.MyApplication;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Api.ApiClient;

public class EnterpriseAdapter extends RecyclerView.Adapter<EnterpriseAdapter.ItemViewHolder> {
    Context context;
    String agency_id, user_id;

    public int showPosition = 0;
    boolean first = false;
    String mac, mc_idx, del_flag;
    Handler handler, hdr;
    CompanyData companyData;
    LinearLayout graphLL;
    ItemViewHolder viewHolder;

    // adapter에 들어갈 list 입니다.
    private ArrayList<AlMachineDatum> items = new ArrayList<>();
    ArrayList<MachineItem> item = new ArrayList<>();

    private EnterpriseAdapter.liveClickListener liveClickListener;

    public interface liveClickListener {
        void clickBtn(Bundle bundle);
    }

    private EnterpriseAdapter.stopClickListener stopClickListener;

    public interface stopClickListener {
        void clickBtn(Bundle bundle);
    }

    public EnterpriseAdapter(Context context, String agency_id, String user_id, CompanyData companyData, EnterpriseAdapter.liveClickListener liveClickListener
            , EnterpriseAdapter.stopClickListener stopClickListener) {
        this.context = context;
        this.agency_id = agency_id;
        this.user_id = user_id;
        this.companyData = companyData;
        this.liveClickListener = liveClickListener;
        this.stopClickListener = stopClickListener;

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String url = msg.getData().getString("url");
                if (url.equals("proc_machine_onoff")) {
                    JsonElement element = new JsonParser().parse(msg.obj.toString());
                    JsonObject result_item = element.getAsJsonObject();
                    Log.d("1234", result_item.toString());
                    if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                        String status;
                        Log.d("result_item@@@", result_item.toString());
                        if (result_item.get("arrayItem").getAsString().equals("MM")) {
                            status = "Staring(" + result_item.get("arrayItem").getAsString() + ")";
                        } else {
                            status = "Stop(" + result_item.get("arrayItem").getAsString() + ")";
                        }

                        MyApplication.stop_ui_change = false;
//                        MyApplication.doing_toggle = false;
                        Intent intent = new Intent(context, MainActivity.class);
                        intent.putExtra("companyData", companyData);
                        context.startActivity(intent);
                        //Toast.makeText(context, status, Toast.LENGTH_LONG).show();
                    } else {
                        //Toast.makeText(context, result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_LONG).show();
                    }
                } else if (url.equals("proc_mqtt_machine_onoff")) {
                    JsonElement element = new JsonParser().parse(msg.obj.toString());
                    JsonObject result_item = element.getAsJsonObject();
                    Log.d("데이터@@@onoff11111", result_item.toString());
                    if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                        String status;
                        if (result_item.get("arrayItem").getAsString().equals("MM")) {
                            status = "Staring(" + result_item.get("arrayItem").getAsString() + ")";
                        } else {
                            status = "Stop(" + result_item.get("arrayItem").getAsString() + ")";
                        }

                        HashMap<String, String> data2 = new HashMap<>();
                        data2.put("mc_idx", mc_idx);
                        data2.put("del_flag", del_flag);
                        new ApiClient(data2, "proc_machine_onoff", handler);

//                        Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        };
    }

    @NonNull
    @Override
    public EnterpriseAdapter.ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // LayoutInflater를 이용하여 전 단계에서 만들었던 item.xml을 inflate 시킵니다.
        // return 인자는 ViewHolder 입니다.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_enterprise, parent, false);
        return new EnterpriseAdapter.ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull EnterpriseAdapter.ItemViewHolder holder, final int position) {
        // Item을 하나, 하나 보여주는(bind 되는) 함수입니다.
        holder.onBind(items.get(position));

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (showPosition != position) {
                    showPosition = position;
                }
                notifyDataSetChanged();
            }
        });

        viewHolder = holder;
    }

    @Override
    public int getItemCount() {
        // RecyclerView의 총 개수 입니다.
        return items.size();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    public void addItem(ArrayList<AlMachineDatum> data) {
        // 외부에서 item을 추가시킬 함수입니다.
        items.clear();
        items.addAll(data);
        notifyDataSetChanged();
    }

    public void clearItem() {
        items.clear();
        notifyDataSetChanged();
    }

    public void data_notify(int k) {
        Log.d("됐다@@@@", "ㅇㅇㅇ");
        viewHolder.adapter.notifyItemChanged(k, null);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    // RecyclerView의 핵심인 ViewHolder 입니다.
    // 여기서 subView를 setting 해줍니다.
    class ItemViewHolder extends RecyclerView.ViewHolder {
        TextView name, lastDt, noneList;
        ImageView arrow;
        LinearLayout content;
        RecyclerView list;
        EnterpriseProdAdapter adapter;
        LinearLayoutManager layoutManager;

        ItemViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.tv_item_enterprise_name);
//            arrow = itemView.findViewById(R.id.iv_item_enterprise_arrow);
            content = itemView.findViewById(R.id.ll_item_enterprise_content);
//            lastDt = itemView.findViewById(R.id.lastDt);
            noneList = itemView.findViewById(R.id.noneList);
            list = itemView.findViewById(R.id.list);

            layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
            list.setLayoutManager(layoutManager);
            adapter = new EnterpriseProdAdapter(context, agency_id, user_id, new EnterpriseProdAdapter.clickListener() {
                @Override
                public void clickBtn(Bundle bundle) {
                    //메인화면 실시간 데이터 받아오기 정지
                    Bundle main_bundle = new Bundle();
                    main_bundle.putBoolean("do_monitoring", false);
                    stopClickListener.clickBtn(main_bundle);

                    mc_idx = bundle.getString("mc_idx");
                    mac = bundle.getString("mac");
                    del_flag = bundle.getString("del_flag");

                    if (TextUtils.isEmpty(mac) || mac == null || mac.equals("0")) {
                        Toast.makeText(context, "연결된 IoT 기기가 없습니다.", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    HashMap<String, String> data = new HashMap<>();
                    data.put("mac", mac);
                    data.put("del_flag", del_flag);
                    new ApiClient(data, "proc_mqtt_machine_onoff", handler);
                }
            }, new EnterpriseProdAdapter.chartClickListener() {
                @Override
                public void clickBtn(Bundle bundle) {

                    //메인화면 실시간 데이터 받아오기 정지
                    Bundle main_bundle = new Bundle();
                    main_bundle.putBoolean("do_monitoring", false);
                    stopClickListener.clickBtn(main_bundle);

                    mc_idx = bundle.getString("mc_idx");
                    mac = bundle.getString("mac");

                    if (TextUtils.isEmpty(mac) || mac == null || mac.equals("0")) {
                        Toast.makeText(context, "연결된 IoT 기기가 없습니다.", Toast.LENGTH_SHORT).show();

                    } else {

//                        MonitoringDialog dialog = new MonitoringDialog(context, agency_id, bundle.getString("pt_idx"), bundle.getString("cp_idx"),
//                                mc_idx, bundle.getString("chart_type"), mac);
//                        dialog.setOnDismissListener(
//                                new DialogInterface.OnDismissListener() {
//                                    @Override
//                                    public void onDismiss(DialogInterface dialogInterface) {
//                                        Bundle main_bundle = new Bundle();
//                                        main_bundle.putBoolean("do_monitoring", false);
//                                        stopClickListener.clickBtn(main_bundle);
//                                    }
//                                });
//                        dialog.show();
                    }
                }
            }, new EnterpriseProdAdapter.timeClickListener() {
                @Override
                public void clickBtn(Bundle bundle) {

                    //메인화면 실시간 데이터 받아오기 정지
                    Bundle main_bundle = new Bundle();
                    main_bundle.putBoolean("do_monitoring", false);
                    stopClickListener.clickBtn(main_bundle);

                    mc_idx = bundle.getString("mc_idx");

                    String incodeUrl = URLEncoder.encode("https://" + agency_id + ".compcare.co.kr/setting/serial/write_machine/" + mc_idx
                            + "?cp_idx=" + bundle.getString("cp_idx") + "&pt_idx=" + bundle.getString("pt_idx"));
                    Intent intent = new Intent(context, WebviewAct.class);
                    intent.putExtra("title", "보유기종 관리");
                    intent.putExtra("url", "https://" + agency_id + ".compcare.co.kr/api/web/" + user_id + "/?url=" + incodeUrl);
                    context.startActivity(intent);
                }

                //MainActivity에 LIVE 버튼을 클릭했을때 받아서 번들을 전달
            }, new EnterpriseProdAdapter.liveClickListener() {
                @Override
                public void clickBtn(Bundle bundle) {

                    liveClickListener.clickBtn(bundle);
                }
            });

            list.setAdapter(adapter);

        }

        void onBind(AlMachineDatum data) {

            name.setText(data.getMcAirline());
//            if (data.getLastExchangeDt().equals("")){
//                lastDt.setText("교환정보 없음");
//            }else{
//                lastDt.setText(data.getLastExchangeDt());
//            }

            if (data.getItems().size() == 0) {
                list.setVisibility(View.GONE);
                noneList.setVisibility(View.VISIBLE);

            } else {
                item.clear();
                item.addAll(data.getItems());
                adapter.addItem(item);
            }
        }
    }
}
