package kr.co.compcareworker.Util.Adapter;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

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

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

import kr.co.compcareworker.Data.ArrayItem;
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;

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

    Context context;
    private String mac;

    private ArrayList<MachineItem> items = new ArrayList<>();
    private ArrayItem<MonitoringData> monitoringArray;

    private ContentAdapter.ItemViewHolder holder;

//    //옵션버튼 클릭 리스너
//    private ContentAdapter.optionListener optionListener;
//
//    public interface optionListener {
//        void clickBtn(Bundle bundle);
//    }

    //차트 클릭 리스너
    private ContentAdapter.chartClickListener chartClickListener;

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

    public ContentAdapter(Context context, ContentAdapter.chartClickListener chartClickListener) {
        setHasStableIds(true);
        this.context = context;
        this.chartClickListener = chartClickListener;
    }

    @NonNull
    @Override
    public ContentAdapter.ItemViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
//        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.del_item_content, viewGroup, false);
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_content_detail, viewGroup, false);
        return new ContentAdapter.ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ContentAdapter.ItemViewHolder holder, int position) {
        holder.onBind(items.get(position));

        if(position > 0) {
            holder.divideTV.setVisibility(View.VISIBLE);
        }

        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(context, 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(context, 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(context, 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(context, 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(context, 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(context, 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(context, 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(context, 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(context, 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;
                        }
                    }

                }
            });
        }
    }

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

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

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

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

    class ItemViewHolder extends RecyclerView.ViewHolder {

        LinearLayout btnLL;
        TextView mc_nameTV, mc_iot_macTV, iot_stateTV, running_timeTV, exchange_dtTV, divideTV, mc_airlineTV;
        Button ct1Btn, ct2Btn, ct3Btn, pr1Btn, pr2Btn, pr3Btn, ntc1Btn, ntc2Btn, pt100Btn;
        Button[] buttons;

        ItemViewHolder(@NonNull View itemView) {
            super(itemView);

            btnLL = itemView.findViewById(R.id.btnLL);
            mc_nameTV = itemView.findViewById(R.id.mc_nameTV);
            mc_iot_macTV = itemView.findViewById(R.id.mc_iot_macTV);
            iot_stateTV = itemView.findViewById(R.id.iot_stateTV);
            running_timeTV = itemView.findViewById(R.id.running_timeTV);
            exchange_dtTV = itemView.findViewById(R.id.exchange_dtTV);
            divideTV = itemView.findViewById(R.id.divideTV);
            mc_airlineTV = itemView.findViewById(R.id.mc_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);

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

        void onBind(MachineItem data) {
            mc_nameTV.setText(data.getProductData().getPdName());
            mc_airlineTV.setText("[ "+data.getMcAirline()+" ]");
            if (data.getMcRunningtime() != null && data.getMcCycle() != null) {
                running_timeTV.setText("( 소모품 시간 : " + data.getMcRunningtime() + " / " + data.getMcCycle() + " )");

                if (Integer.parseInt(data.getMcRunningtime()) >= Integer.parseInt(data.getMcCycle())) {
                    running_timeTV.setTextColor(Color.RED);
                }

                Calendar cal = Calendar.getInstance();
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                Date date = null;
                if (data.getMcExchangedt() != null) {
                    try {
                        date = df.parse(data.getMcExchangedt().toString());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    cal.setTime(date);
                    if (data.getMcCycleYear() != null) {
                        cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
                        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + Integer.parseInt(data.getMcCycleYear()));
                        exchange_dtTV.setText("( 교환일 : "+data.getMcExchangedt().toString()+" / 예정일 : "+df.format(cal.getTime()) +" )");

                    } else {
                        exchange_dtTV.setText("( 교환일 : "+data.getMcExchangedt().toString()+" / 예정일 : - )");
                    }
                }
            }

            if (data.getMcIotMac() != null){
                mc_iot_macTV.setText("MAC : " + data.getMcIotMac());
                iot_stateTV.setVisibility(View.VISIBLE);
                btnLL.setVisibility(View.VISIBLE);
            } else {
                mc_iot_macTV.setText("MAC 없음");
                iot_stateTV.setVisibility(View.GONE);
                btnLL.setVisibility(View.GONE);
            }

            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_stateTV.setText("[ 기동중 ]");
                    iot_stateTV.setTextColor(context.getColor(R.color.light_blue));

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

                    iot_stateTV.setText("[ 트립 ]");
                    iot_stateTV.setTextColor(context.getColor(R.color.red));

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

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

                    if (monitoringData.getCurrent1Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[0], monitoringData.getCurrent1(), monitoringData.getCurrent1Max(),
                                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 (monitoringData.getCurrent2Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[1], monitoringData.getCurrent2(), monitoringData.getCurrent2Max(),
                                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 (monitoringData.getCurrent3Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[2], monitoringData.getCurrent3(), monitoringData.getCurrent3Max(),
                                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 (monitoringData.getPressure1Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[3], monitoringData.getPressure1(), monitoringData.getPressure1Max(),
                                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 (monitoringData.getPressure2Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[4], monitoringData.getPressure2(), monitoringData.getPressure2Max(),
                                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 (monitoringData.getPressure3Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[5], monitoringData.getPressure3(), monitoringData.getPressure3Max(),
                                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 (monitoringData.getTempNtcMax() != null) {
                        Common.getInstance().condition_status_iot(buttons[6], monitoringData.getTempNtc(), monitoringData.getTempNtcMax(),
                                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 (monitoringData.getTempNtc2Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[7], monitoringData.getTempNtc2(), monitoringData.getTempNtc2Max(),
                                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 (monitoringData.getTempPt100Max() != null) {
                        Common.getInstance().condition_status_iot(buttons[8], monitoringData.getTempPt100(), monitoringData.getTempPt100Max(),
                                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");
                    }
                }
            }
        }
    }
}
