package kr.co.compcarecompany.Util.Adapter;

import android.app.Activity;
import android.graphics.Color;
import android.os.Handler;
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.compcarecompany.Data.Product.MachineItem;
import kr.co.compcarecompany.Data.Product.MonitoringData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.CustomView.MonitoringDialog;

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

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

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

    @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));
                holder.iot_detail_running_timeTV.setTextColor(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;
                        }
                    }

                }
            });
        }
    }

    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_running_timeTV1, iot_detail_stateTV, iot_detail_macTV, iot_detail_make_dateTV, iot_detail_cp_nameTV, iot_detail_qrTV;
        Button ct1Btn, ct2Btn, ct3Btn, pr1Btn, pr2Btn, pr3Btn, ntc1Btn, ntc2Btn, pt100Btn;
        Button[] buttons;
        ProgressBar mc_runningPB;

        ItemViewHolder(View itemView) {
            super(itemView);
            iot_detail_cp_nameTV = itemView.findViewById(R.id.iot_detail_cp_nameTV);
            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_running_timeTV1 = itemView.findViewById(R.id.iot_detail_running_timeTV1);
            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);
            iot_detail_qrTV = itemView.findViewById(R.id.iot_detail_qrTV);

            mc_runningPB = itemView.findViewById(R.id.mc_runningPB);

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

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

            if (data.getMcRunningtime() != null && data.getMcCycle() != null) {
                iot_detail_running_timeTV.setText("소모품 시간 : " + data.getMcRunningtime() + " / " + data.getMcCycle());


                if (Integer.parseInt(data.getMcRunningtime()) >= Integer.parseInt(data.getMcCycle())) {
                    iot_detail_running_timeTV.setTextColor(Color.RED);
                } else {
                    iot_detail_running_timeTV.setTextColor(Color.BLACK);
                }
            } else {
                iot_detail_running_timeTV.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, null, data.getMcIotMac());
            }


            if(monitoringData != null && data.getMcYeonYn().equals("Y") && monitoringData.getMqttYeonType() != null && monitoringData.getMqttYeonType().equals("7") ) {
                iot_detail_running_timeTV1.setTextColor(Color.BLUE);
                iot_detail_running_timeTV1.setText(data.getMcAirline() + "->연동제어 : " + "MASTER ( " + data.getMcCrossNum() +" )");

            }else if(monitoringData != null && data.getMcYeonYn().equals("Y") && monitoringData.getMqttYeonType() != null && monitoringData.getMqttYeonType().equals("8") ) {
                iot_detail_running_timeTV1.setTextColor(Color.BLUE);
                iot_detail_running_timeTV1.setText(data.getMcAirline() + "->연동제어 : " + "SLAVE ( " + data.getMcCrossNum() +" )");

            }else{
                iot_detail_running_timeTV1.setText(" ");
            }

            if(data.getQrCode() != null) {
                iot_detail_qrTV.setText("QR 코드 : "+data.getQrCode());
            }

            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("기계 제조일자 : 입력 없음");
            }



            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 != null && monitoringData.getInverterError() != null && monitoringData.getPowerError() != null &&
                        (monitoringData.getInverterError().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);
                }
            }
            //모니터링 데이터를 가져오는 것을 실패했을 때
            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 {
                        buttons[i].setText("PT100\nOFF");
                    }
                }
            }
        }
    }
}
