package kr.co.compcareworker.Util.Adapter;

import android.app.Activity;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import kr.co.compcareworker.Data.Company.Machine.MachineItem;
import kr.co.compcareworker.Data.Company.Machine.Product.MonitoringData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Common;
import kr.co.compcareworker.Util.CustomView.MonitoringDialog;
import kr.co.compcareworker.Util.CustomView.MonitoringReportDialog;

public class IoTProdDetailRecyclerAdapter extends RecyclerView.Adapter<IoTProdDetailRecyclerAdapter.ItemViewHolder> {

    private Activity activity;
    Handler handler;
    private ArrayList<MachineItem> items = new ArrayList<>();
    private IoTProdDetailRecyclerAdapter.iotClickListener iotClickListener;


    public IoTProdDetailRecyclerAdapter(Activity activity, Handler handler, IoTProdDetailRecyclerAdapter.iotClickListener iotClickListener) {
        this.activity = activity;
        this.handler = handler;
        this.iotClickListener = iotClickListener;
    }

    public interface iotClickListener {
        void clickBtn(Bundle bundle);
        void initializationBtn(MachineItem item);
    }

    @NonNull
    @Override
    public IoTProdDetailRecyclerAdapter.ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_iot_list_detail_chart, parent, false);
        return new IoTProdDetailRecyclerAdapter.ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull IoTProdDetailRecyclerAdapter.ItemViewHolder holder, int position) {
        try {
            holder.onBind(items.get(position));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (items.get(position).getMcRunningtime() != null && items.get(position).getMcCycle() != null) {

            int cycle = Integer.parseInt(Common.getInstance().isNullToZero(items.get(position).getMcCycle()));
            int runningTime = Integer.parseInt(Common.getInstance().isNullToZero(items.get(position).getMcRunningtime()));

            if (runningTime > cycle) {
                holder.mc_runningPB.setProgressTintList(activity.getApplicationContext().getColorStateList(R.color.red));
                runningTime = cycle;

            } else {
                holder.iot_detail_running_timeTV.setText(runningTime + "");
            }

            holder.iot_detail_running_timeTV.setText("소모품 시간 : " + items.get(position).getMcRunningtime() + " / " + items.get(position).getMcCycle());
            double per;
            if (cycle == 0 && runningTime != 0) {
                per = 1000;
            } else {
                per = ((double) runningTime / (double) cycle) * 1000;
            }

            holder.mc_runningPB.setMax(1000);
            holder.mc_runningPB.setProgress((int) per);

        } else {
            holder.iot_detail_running_timeTV.setText("소모품 시간 : 입력 없음 ");
        }

        for (int i = 0; i < holder.buttons.length; i++) {
            int finalI = i;
            holder.buttons[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (finalI) {
                        case 0: {
                            MonitoringDialog dialog = new MonitoringDialog(activity, items.get(position).getAgIdx(), items.get(position).getPtIdx(), items.get(position).getCpIdx()
                                    , items.get(position).getMcIdx(), "current1", items.get(position).getMcIotMac(), items.get(position));
                            dialog.show();
                            break;
                        }
                        case 1: {
                            MonitoringDialog dialog = new MonitoringDialog(activity, items.get(position).getAgIdx(), items.get(position).getPtIdx(), items.get(position).getCpIdx()
                                    , items.get(position).getMcIdx(), "current2", items.get(position).getMcIotMac(), items.get(position));
                            dialog.show();
                            break;
                        }
                        case 2: {
                            MonitoringDialog dialog = new MonitoringDialog(activity, items.get(position).getAgIdx(), items.get(position).getPtIdx(), items.get(position).getCpIdx()
                                    , items.get(position).getMcIdx(), "current3", items.get(position).getMcIotMac(), items.get(position));
                            dialog.show();
                            break;
                        }
                        case 3: {
                            MonitoringDialog dialog = new MonitoringDialog(activity, items.get(position).getAgIdx(), items.get(position).getPtIdx(), items.get(position).getCpIdx()
                                    , items.get(position).getMcIdx(), "pressure1", items.get(position).getMcIotMac(), items.get(position));
                            dialog.show();
                            break;
                        }
                        case 4: {
                            MonitoringDialog dialog = new MonitoringDialog(activity, items.get(position).getAgIdx(), items.get(position).getPtIdx(), items.get(position).getCpIdx()
                                    , items.get(position).getMcIdx(), "pressure2", items.get(position).getMcIotMac(), items.get(position));
                            dialog.show();
                            break;
                        }
                        case 5: {
                            MonitoringDialog dialog = new MonitoringDialog(activity, items.get(position).getAgIdx(), items.get(position).getPtIdx(), items.get(position).getCpIdx()
                                    , items.get(position).getMcIdx(), "pressure3", items.get(position).getMcIotMac(), items.get(position));
                            dialog.show();
                            break;
                        }
                        case 6: {
                            MonitoringDialog dialog = new MonitoringDialog(activity, items.get(position).getAgIdx(), items.get(position).getPtIdx(), items.get(position).getCpIdx()
                                    , items.get(position).getMcIdx(), "temperatureNtc", items.get(position).getMcIotMac(), items.get(position));
                            dialog.show();
                            break;
                        }
                        case 7: {
                            MonitoringDialog dialog = new MonitoringDialog(activity, items.get(position).getAgIdx(), items.get(position).getPtIdx(), items.get(position).getCpIdx()
                                    , items.get(position).getMcIdx(), "temperatureNtc2", items.get(position).getMcIotMac(), items.get(position));
                            dialog.show();
                            break;
                        }
                        case 8: {
                            MonitoringDialog dialog = new MonitoringDialog(activity, items.get(position).getAgIdx(), items.get(position).getPtIdx(), items.get(position).getCpIdx()
                                    , items.get(position).getMcIdx(), "temperaturePt", items.get(position).getMcIotMac(), items.get(position));
                            dialog.show();
                            break;
                        }
                        case 9: {
                            MonitoringDialog dialog = new MonitoringDialog(activity, items.get(position).getAgIdx(), items.get(position).getPtIdx(), items.get(position).getCpIdx()
                                    , items.get(position).getMcIdx(), "power_consumption", items.get(position).getMcIotMac(), items.get(position));
                            dialog.show();
                            break;
                        }
                    }

                }
            });
        }

        //데이터 분석 클릭리스너
        holder.monitoring_reportBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Bundle bundle = new Bundle();
                bundle.putString("mc_idx", items.get(position).getMcIdx());
                bundle.putString("ag_idx", items.get(position).getAgIdx());
                bundle.putString("pt_idx", items.get(position).getPtIdx());

                iotClickListener.clickBtn(bundle);
            }
        });

        //소모품 초기화 클릭리스너
        holder.machine_resetBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                iotClickListener.initializationBtn(items.get(position));
            }
        });
    }

    public void addAll(ArrayList<MachineItem> lst) {
        items.clear();
        items.addAll(lst);
        notifyDataSetChanged();
    }

    public void addItem(MachineItem data) {
        items.add(data);
        notifyDataSetChanged();
    }

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

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

    @Override
    public int getItemCount() {
        return items.size();
    }

    class ItemViewHolder extends RecyclerView.ViewHolder {
        TextView iot_detail_mc_nameTV, iot_detail_airlineTV, iot_detail_running_timeTV, iot_detail_stateTV, iot_detail_macTV, iot_detail_make_dateTV;
        Button ct1Btn, ct2Btn, ct3Btn, pr1Btn, pr2Btn, pr3Btn, ntc1Btn, ntc2Btn, pt100Btn, power_consumptionBtn, monitoring_reportBtn, machine_resetBtn;
        Button[] buttons;
        ProgressBar mc_runningPB;

        ItemViewHolder(View itemView) {
            super(itemView);
            iot_detail_mc_nameTV = itemView.findViewById(R.id.iot_detail_mc_nameTV);
            iot_detail_airlineTV = itemView.findViewById(R.id.iot_detail_airlineTV);
            ct1Btn = itemView.findViewById(R.id.ct1Btn);
            ct2Btn = itemView.findViewById(R.id.ct2Btn);
            ct3Btn = itemView.findViewById(R.id.ct3Btn);
            pr1Btn = itemView.findViewById(R.id.pr1Btn);
            pr2Btn = itemView.findViewById(R.id.pr2Btn);
            pr3Btn = itemView.findViewById(R.id.pr3Btn);
            ntc1Btn = itemView.findViewById(R.id.ntc1Btn);
            ntc2Btn = itemView.findViewById(R.id.ntc2Btn);
            pt100Btn = itemView.findViewById(R.id.pt100Btn);
            iot_detail_running_timeTV = itemView.findViewById(R.id.iot_detail_running_timeTV);
            iot_detail_stateTV = itemView.findViewById(R.id.iot_detail_stateTV);
            iot_detail_macTV = itemView.findViewById(R.id.iot_detail_macTV);
            iot_detail_make_dateTV = itemView.findViewById(R.id.iot_detail_make_dateTV);
            mc_runningPB = itemView.findViewById(R.id.mc_runningPB);
            power_consumptionBtn = itemView.findViewById(R.id.power_consumptionBtn);
            monitoring_reportBtn = itemView.findViewById(R.id.monitoring_reportBtn);
            machine_resetBtn = itemView.findViewById(R.id.machine_resetBtn);

            buttons = new Button[]{ct1Btn, ct2Btn, ct3Btn, pr1Btn, pr2Btn, pr3Btn, ntc1Btn, ntc2Btn, pt100Btn, power_consumptionBtn};
        }

        void onBind(MachineItem data) throws ParseException {
            iot_detail_mc_nameTV.setText(data.getPdName());
            iot_detail_airlineTV.setText(data.getMcAirline());
            iot_detail_macTV.setText("( MAC : " + data.getMcIotMac() + " )");

            if (data.getMcMakedt() != null) {

                SimpleDateFormat beforeSDF = new SimpleDateFormat("yyyy-MM-dd");
                Date beforeDate = beforeSDF.parse(data.getMcMakedt());
                SimpleDateFormat afterSDF = new SimpleDateFormat("yy.MM.dd");
                String afterDate = afterSDF.format(beforeDate);
                iot_detail_make_dateTV.setText("( 기계 제조일자 : " + afterDate + " )");
            } else {
                iot_detail_make_dateTV.setText("( 기계 제조일자 : 입력 없음 )");
            }

            MonitoringData monitoringData;

            if (data.getMonitoring() != null) {
                monitoringData = data.getMonitoring().get(0);
            } else {

                monitoringData = new MonitoringData(null, null, null, null, null, null, null, null, null, data.getMcIotMac());
            }

            if (monitoringData != null) {

                if (monitoringData.getRunning() != null && monitoringData.getRunning().equals("1")) {
                    iot_detail_stateTV.setText("[ 기동중 ]");
                    iot_detail_stateTV.setTextColor(activity.getColor(R.color.light_blue));

                } else if (monitoringData.getInverter_Error() != null && monitoringData.getPowerError() != null && (monitoringData.getInverter_Error().equals("1") || monitoringData.getPowerError().equals("1"))) {

                    iot_detail_stateTV.setText("[ 트립 ]");
                    iot_detail_stateTV.setTextColor(activity.getColor(R.color.red));

                } else {
                    iot_detail_stateTV.setText("[ 기동정지 ]");
                    iot_detail_stateTV.setTextColor(activity.getColor(R.color.dark_gray));
                }

                if (monitoringData.getCurrent1() != null) {
                    buttons[0].setText("전류1\n" + Common.getInstance().valueConvert(monitoringData.getCurrent1()));

                    if (data.getMcCurrent1Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[0], monitoringData.getCurrent1(), data.getMcCurrent1Max(),
                                data.getMcCurrent1Up(), data.getMcCurrent1Down());
                    } else {
                        Common.getInstance().condition_status_iot(buttons[0], monitoringData.getCurrent1(), "15",
                                data.getMcCurrent1Up(), data.getMcCurrent1Down());
                    }
                } else {
                    buttons[0].setText("전류1\nOFF");
                    buttons[0].setBackgroundResource(R.drawable.border_gray_fill_lgray_round);
                }

                if (monitoringData.getCurrent2() != null) {
                    buttons[1].setText("전류2\n" + Common.getInstance().valueConvert(monitoringData.getCurrent2()));

                    if (data.getMcCurrent2Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[1], monitoringData.getCurrent2(), data.getMcCurrent2Max(),
                                data.getMcCurrent2Up(), data.getMcCurrent2Down());
                    } else {
                        Common.getInstance().condition_status_iot(buttons[1], monitoringData.getCurrent2(), "15",
                                data.getMcCurrent2Up(), data.getMcCurrent2Down());
                    }
                } else {
                    buttons[1].setText("전류2\nOFF");
                    buttons[1].setBackgroundResource(R.drawable.border_gray_fill_lgray_round);
                }

                if (monitoringData.getCurrent3() != null) {
                    buttons[2].setText("전류3\n" + Common.getInstance().valueConvert(monitoringData.getCurrent3()));

                    if (data.getMcCurrent3Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[2], monitoringData.getCurrent3(), data.getMcCurrent3Max(),
                                data.getMcCurrent3Up(), data.getMcCurrent3Down());
                    } else {
                        Common.getInstance().condition_status_iot(buttons[2], monitoringData.getCurrent3(), "15",
                                data.getMcCurrent3Up(), data.getMcCurrent3Down());
                    }
                } else {
                    buttons[2].setText("전류3\nOFF");
                    buttons[2].setBackgroundResource(R.drawable.border_gray_fill_lgray_round);
                }

                if (monitoringData.getPressure1() != null) {
                    buttons[3].setText("압력1\n" + Common.getInstance().valueConvert1(monitoringData.getPressure1()));

                    if (data.getMcPressure1Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[3], monitoringData.getPressure1(), data.getMcPressure1Max(),
                                data.getMcPressure1Up(), data.getMcPressure1Down());
                    } else {
                        Common.getInstance().condition_status_iot(buttons[3], monitoringData.getPressure1(), "10",
                                data.getMcPressure1Up(), data.getMcPressure1Down());
                    }
                } else {
                    buttons[3].setText("압력1\nOFF");
                    buttons[3].setBackgroundResource(R.drawable.border_gray_fill_lgray_round);
                }

                if (monitoringData.getPressure2() != null) {
                    buttons[4].setText("압력2\n" + Common.getInstance().valueConvert1(monitoringData.getPressure2()));

                    if (data.getMcPressure2Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[4], monitoringData.getPressure2(), data.getMcPressure2Max(),
                                data.getMcPressure2Up(), data.getMcPressure2Down());
                    } else {
                        Common.getInstance().condition_status_iot(buttons[4], monitoringData.getPressure2(), "10",
                                data.getMcPressure2Up(), data.getMcPressure2Down());
                    }
                } else {
                    buttons[4].setText("압력2\nOFF");
                    buttons[4].setBackgroundResource(R.drawable.border_gray_fill_lgray_round);
                }


                if (monitoringData.getPressure3() != null) {
                    buttons[5].setText("압력3\n" + Common.getInstance().valueConvert1(monitoringData.getPressure3()));

                    if (data.getMcPressure3Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[5], monitoringData.getPressure3(), data.getMcPressure3Max(),
                                data.getMcPressure3Up(), data.getMcPressure3Down());
                    } else {
                        Common.getInstance().condition_status_iot(buttons[5], monitoringData.getPressure3(), "10",
                                data.getMcPressure3Up(), data.getMcPressure3Down());
                    }
                } else {
                    buttons[5].setText("압력3\nOFF");
                    buttons[5].setBackgroundResource(R.drawable.border_gray_fill_lgray_round);
                }


                if (monitoringData.getTempNtc() != null) {
                    buttons[6].setText("NTC1\n" + Common.getInstance().valueConvert(monitoringData.getTempNtc()));

                    if (data.getMcTempNtcMax() != null) {
                        Common.getInstance().condition_status_iot(buttons[6], monitoringData.getTempNtc(), data.getMcTempNtcMax(),
                                data.getMcTempNtcUp(), data.getMcTempNtcDown());
                    } else {
                        Common.getInstance().condition_status_iot(buttons[6], monitoringData.getTempNtc(), "110",
                                data.getMcTempNtcUp(), data.getMcTempNtcDown());
                    }
                } else {
                    buttons[6].setText("NTC1\nOFF");
                    buttons[6].setBackgroundResource(R.drawable.border_gray_fill_lgray_round);
                }


                if (monitoringData.getTempNtc2() != null) {
                    buttons[7].setText("NTC2\n" + Common.getInstance().valueConvert(monitoringData.getTempNtc2()));

                    if (data.getMcTempNtc2Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[7], monitoringData.getTempNtc2(), data.getMcTempNtc2Max(),
                                data.getMcTempNtc2Up(), data.getMcTempNtc2Down());
                    } else {
                        Common.getInstance().condition_status_iot(buttons[7], monitoringData.getTempNtc2(), "110",
                                data.getMcTempNtc2Up(), data.getMcTempNtc2Down());
                    }
                } else {
                    buttons[7].setText("NTC2\nOFF");
                    buttons[7].setBackgroundResource(R.drawable.border_gray_fill_lgray_round);
                }

                if (monitoringData.getTempPt100() != null) {
                    buttons[8].setText("PT100\n" + Common.getInstance().valueConvert(monitoringData.getTempPt100()));

                    if (data.getMcTempPtMax() != null) {
                        Common.getInstance().condition_status_iot(buttons[8], monitoringData.getTempPt100(), data.getMcTempPtMax(),
                                data.getMcTempPtUp(), data.getMcTempPtDown());
                    } else {
                        Common.getInstance().condition_status_iot(buttons[8], monitoringData.getTempPt100(), "110",
                                data.getMcTempPtUp(), data.getMcTempPtDown());
                    }
                } else {
                    buttons[8].setText("PT100\nOFF");
                    buttons[8].setBackgroundResource(R.drawable.border_gray_fill_lgray_round);
                }

                if (monitoringData.getPowerConsumption() != null) {
                    buttons[9].setText("소비전력 "+ Common.getInstance().valueConvert((Integer.parseInt(monitoringData.getPowerConsumption()) / 1000)+"kW"));
                    buttons[9].setBackgroundResource(R.drawable.bg_green_round_opa40);
                } else {
                    buttons[9].setText("소비전력 OFF");
                    buttons[9].setBackgroundResource(R.drawable.border_gray_fill_lgray_round);
                }
            }
            //모니터링 데이터를 가져오는 것을 실패했을 때
            else {

                for (int i = 0; i < buttons.length; i++) {
                    buttons[i].setBackgroundResource(R.drawable.border_gray_fill_lgray_round);
                    if (i < 3) {
                        buttons[i].setText("전류" + (i + 1) + "\nOFF");
                    } else if (i < 6) {
                        buttons[i].setText("압력" + (i % 3 + 1) + "\nOFF");
                    } else if (i < 8) {
                        buttons[i].setText("NTC" + (i % 3 + 1) + "\nOFF");
                    } else if (i < 9){
                        buttons[i].setText("PT100\nOFF");
                    } else {
                        buttons[i].setText("소비전력 OFF");
                    }
                }
            }
        }
    }
}
