package kr.co.compcareworker.Util.Adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

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.Activity.FragmentActivity;
import kr.co.compcareworker.Data.Company.Machine.AlarmData;
import kr.co.compcareworker.Data.Company.Machine.MachineItem;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Common;
import kr.co.compcareworker.Util.CustomView.MemberCallListDialog;
import kr.co.compcareworker.Util.CustomView.MonitoringDialog;

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

    // adapter에 들어갈 list 입니다.
    private ArrayList<AlarmData> items = new ArrayList<>();
    private Context context;
    private Handler handler;

    private AlarmListAdapter.completeListener completeListener;

    public interface completeListener {
        void onClick(String mcl_idx);
        void onMemoSave(String mcl_idx, String memo);
        void onInvoice(String cp_idx);
    }

    private OnLoadMoreListener onLoadMoreListener;

    public interface OnLoadMoreListener {
        void onLoadMore(int position);
    }

    public AlarmListAdapter(Context context, Handler handler, AlarmListAdapter.completeListener completeListener, OnLoadMoreListener onLoadMoreListener) {
        this.handler = handler;
        this.context = context;
        this.completeListener = completeListener;
        this.onLoadMoreListener = onLoadMoreListener;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {

        holder.onBind(items.get(position));

        SimpleDateFormat beforeSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        holder.alarm_dateTV.setText("-");
        Date beforeDate = null;
        try {
            beforeDate = beforeSDF.parse(items.get(position).getPushDt());
            SimpleDateFormat afterSDF = new SimpleDateFormat("yyyy.MM.dd HH:mm");
            String afterDate = afterSDF.format(beforeDate);
            holder.alarm_dateTV.setText(afterDate);
        } 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(context.getColorStateList(R.color.red));
                runningTime = cycle;

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

            holder.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.running_timeTV.setText("소모품 시간 : 입력 없음 ");
        }


        if (position == getItemCount() - 1) {
            if (onLoadMoreListener != null) {
                onLoadMoreListener.onLoadMore(position);
            }
        }

        //연락처 클릭리스너
        holder.alarm_call_listLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MemberCallListDialog dialog = new MemberCallListDialog(context, handler, items.get(position).getPtIdx());
                dialog.show();
            }
        });

        //접수 클릭리스너
        holder.alarm_serviceLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, FragmentActivity.class);
                intent.putExtra("title", "서비스 접수");
                intent.putExtra("type", "service_register");
                intent.putExtra("value1", items.get(position).getCpIdx());
                context.startActivity(intent);
            }
        });

        //완료처리 클릭리스너
        holder.alarm_completeTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                completeListener.onClick(items.get(position).getMclIdx());
            }
        });

        //상세보기 클릭리스너
        holder.alarm_monitoringLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String type = "";
                switch (items.get(position).getSensor()) {
                    case "1":
                        type = "current1";
                        break;
                    case "2":
                        type = "current2";
                        break;
                    case "3":
                        type = "current3";
                        break;
                    case "4":
                        type = "pressure1";
                        break;
                    case "5":
                        type = "pressure2";
                        break;
                    case "6":
                        type = "pressure3";
                        break;
                    case "7":
                        type = "temperatureNtc";
                        break;
                    case "8":
                        type = "temperaturePt";
                        break;
                    case "9":
                        type = "temperatureNtc2";
                        break;
                }

                showDetail(type, items.get(position));
            }
        });

        //화살표 클릭리스너
        holder.alarm_detail_info_showIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (holder.alarm_detail_infoLL.getVisibility()) {
                    case View.GONE:
                        holder.alarm_detail_infoLL.setVisibility(View.VISIBLE);
                        holder.alarm_detail_info_showIV.setImageResource(R.drawable.icon_arrow_up_gray);
                        break;
                    default:
                        holder.alarm_detail_infoLL.setVisibility(View.GONE);
                        holder.alarm_detail_info_showIV.setImageResource(R.drawable.icon_arrow_down_gray2);
                        break;
                }
            }
        });

        //메모 저장 클릭리스너
        holder.alarm_checked_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                completeListener.onMemoSave(items.get(position).getMclIdx(), holder.alarm_checked_memoET.getText().toString());
            }
        });

        //거내내역 클릭리스너
        holder.alarm_invoice_listLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                completeListener.onInvoice(items.get(position).getCpIdx());
            }
        });

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String type = "";

                if (v == holder.ct1TV) {
                    type = "current1";
                } else if (v == holder.ct2TV) {
                    type = "current2";
                } else if (v == holder.ct3TV) {
                    type = "current3";
                } else if (v == holder.pt1TV) {
                    type = "pressure1";
                } else if (v == holder.pt2TV) {
                    type = "pressure2";
                } else if (v == holder.pt3TV) {
                    type = "pressure3";
                } else if (v == holder.temp1TV) {
                    type = "temperatureNtc";
                } else if (v == holder.temp2TV) {
                    type = "temperaturePt";
                } else if (v == holder.temp3TV) {
                    type = "temperatureNtc2";
                }
                showDetail(type, items.get(position));
            }
        };

        holder.ct1TV.setOnClickListener(clickListener);
        holder.ct2TV.setOnClickListener(clickListener);
        holder.ct3TV.setOnClickListener(clickListener);
        holder.pt1TV.setOnClickListener(clickListener);
        holder.pt2TV.setOnClickListener(clickListener);
        holder.pt3TV.setOnClickListener(clickListener);
        holder.temp1TV.setOnClickListener(clickListener);
        holder.temp2TV.setOnClickListener(clickListener);
        holder.temp3TV.setOnClickListener(clickListener);
    }

    void showDetail(String type, AlarmData data) {

        MachineItem machineItem = new MachineItem();
        machineItem.setMcCurrent1Max(data.getMcCurrent1Max());
        machineItem.setMcCurrent1Up(data.getMcCurrent1Up());
        machineItem.setMcCurrent1Down(data.getMcCurrent1Down());

        machineItem.setMcCurrent2Max(data.getMcCurrent2Max());
        machineItem.setMcCurrent2Up(data.getMcCurrent2Up());
        machineItem.setMcCurrent2Down(data.getMcCurrent2Down());

        machineItem.setMcCurrent3Max(data.getMcCurrent3Max());
        machineItem.setMcCurrent3Up(data.getMcCurrent3Up());
        machineItem.setMcCurrent3Down(data.getMcCurrent3Down());

        machineItem.setMcPressure1Max(data.getMcPressure1Max());
        machineItem.setMcPressure1Up(data.getMcPressure1Up());
        machineItem.setMcPressure1Down(data.getMcPressure1Down());

        machineItem.setMcPressure2Max(data.getMcPressure2Max());
        machineItem.setMcPressure2Up(data.getMcPressure2Up());
        machineItem.setMcPressure2Down(data.getMcPressure2Down());

        machineItem.setMcPressure3Max(data.getMcPressure3Max());
        machineItem.setMcPressure3Up(data.getMcPressure3Up());
        machineItem.setMcPressure3Down(data.getMcPressure3Down());

        machineItem.setMcTempNtcMax(data.getMcTempNtcMax());
        machineItem.setMcTempNtcUp(data.getMcTempNtcUp());
        machineItem.setMcTempNtcDown(data.getMcTempNtcDown());

        machineItem.setMcTempNtc2Max(data.getMcTempNtc2Max());
        machineItem.setMcTempNtc2Up(data.getMcTempNtc2Up());
        machineItem.setMcTempNtc2Down(data.getMcTempNtc2Down());

        machineItem.setMcTempPtMax(data.getMcTempPtMax());
        machineItem.setMcTempPtUp(data.getMcTempPtUp());
        machineItem.setMcTempPtDown(data.getMcTempPtDown());

        MonitoringDialog dialog = new MonitoringDialog(context, type, data.getMcIotMac(), machineItem, data.getPushDt());
        dialog.show();
    }

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

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

    public void addItemMore(ArrayList<AlarmData> lst) {
        items.addAll(lst);
        notifyItemRangeChanged(0, items.size());
    }

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

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

    // RecyclerView의 핵심인 ViewHolder 입니다.
    // 여기서 subView를 setting 해줍니다.
    class ItemViewHolder extends RecyclerView.ViewHolder {

        ImageView alarm_stateIV, alarm_detail_info_showIV;
        TextView alarm_pt_nameTV, alarm_cp_nameTV, alarm_pd_nameTV, alarm_mc_iot_macTV, alarm_mc_airlineTV, alarm_cp_addrTV,
                alarm_infoTV, alarm_completeTV, alarm_dateTV, alarm_checked_memberTV, alarm_mc_qrTV, running_timeTV;
        LinearLayout alarm_call_listLL, alarm_serviceLL, alarm_detail_infoLL, alarm_monitoringLL, monitoring_chart_btnLL, alarm_invoice_listLL;
        TextView ct1TV, ct2TV, ct3TV, pt1TV, pt2TV, pt3TV, temp1TV, temp2TV, temp3TV, mc_nameTV, alarm_checked_saveTV;
        EditText alarm_checked_memoET;
        ProgressBar mc_runningPB;

        ItemViewHolder(View itemView) {
            super(itemView);
            alarm_stateIV = itemView.findViewById(R.id.alarm_stateIV);
            alarm_detail_info_showIV = itemView.findViewById(R.id.alarm_detail_info_showIV);
            alarm_pt_nameTV = itemView.findViewById(R.id.alarm_pt_nameTV);
            alarm_cp_nameTV = itemView.findViewById(R.id.alarm_cp_nameTV);
            alarm_pd_nameTV = itemView.findViewById(R.id.alarm_pd_nameTV);
            alarm_mc_iot_macTV = itemView.findViewById(R.id.alarm_mc_iot_macTV);
            alarm_mc_airlineTV = itemView.findViewById(R.id.alarm_mc_airlineTV);
            alarm_cp_addrTV = itemView.findViewById(R.id.alarm_cp_addrTV);
            alarm_infoTV = itemView.findViewById(R.id.alarm_infoTV);
            alarm_completeTV = itemView.findViewById(R.id.alarm_completeTV);
            alarm_call_listLL = itemView.findViewById(R.id.alarm_call_listLL);
            alarm_serviceLL = itemView.findViewById(R.id.alarm_serviceLL);
            alarm_detail_infoLL = itemView.findViewById(R.id.alarm_detail_infoLL);
            alarm_dateTV = itemView.findViewById(R.id.alarm_dateTV);
            alarm_monitoringLL = itemView.findViewById(R.id.alarm_monitoringLL);
            alarm_checked_memberTV = itemView.findViewById(R.id.alarm_checked_memberTV);
            alarm_mc_qrTV = itemView.findViewById(R.id.alarm_mc_qrTV);

            monitoring_chart_btnLL = itemView.findViewById(R.id.monitoring_chart_btnLL);
            ct1TV = itemView.findViewById(R.id.ct1TV);
            ct2TV = itemView.findViewById(R.id.ct2TV);
            ct3TV = itemView.findViewById(R.id.ct3TV);
            pt1TV = itemView.findViewById(R.id.pt1TV);
            pt2TV = itemView.findViewById(R.id.pt2TV);
            pt3TV = itemView.findViewById(R.id.pt3TV);
            temp1TV = itemView.findViewById(R.id.temp1TV);
            temp2TV = itemView.findViewById(R.id.temp2TV);
            temp3TV = itemView.findViewById(R.id.temp3TV);

            mc_nameTV = itemView.findViewById(R.id.mc_nameTV);
            alarm_checked_saveTV = itemView.findViewById(R.id.alarm_checked_saveTV);
            alarm_checked_memoET = itemView.findViewById(R.id.alarm_checked_memoET);
            alarm_invoice_listLL = itemView.findViewById(R.id.alarm_invoice_listLL);

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

        void onBind(AlarmData data) {

            alarm_pt_nameTV.setText(data.getPtName());
            alarm_cp_nameTV.setText("[ " + data.getCpName() + " ]");
            alarm_pd_nameTV.setText(data.getPdName());
            mc_nameTV.setText(data.getPdName());

            String wo_memo = "(주의) ";

            switch (data.getSensor()) {
                case "1":
                    wo_memo = wo_memo + "전류 1 : " + Common.getInstance().valueConvert(data.getSensorValue()) + "A ";
                    alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_yellow);
                    break;
                case "2":
                    wo_memo = wo_memo + "전류 2 : " + Common.getInstance().valueConvert(data.getSensorValue()) + "A ";
                    alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_yellow);
                    break;
                case "3":
                    wo_memo = wo_memo + "전류 3 : " + Common.getInstance().valueConvert(data.getSensorValue()) + "A ";
                    alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_yellow);
                    break;
                case "4":
                    wo_memo = wo_memo + "압력 1 : " + Common.getInstance().valueConvert1(data.getSensorValue()) + "Bar ";
                    alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_yellow);
                    break;
                case "5":
                    wo_memo = wo_memo + "압력 2 : " + Common.getInstance().valueConvert1(data.getSensorValue()) + "Bar ";
                    alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_yellow);
                    break;
                case "6":
                    wo_memo = wo_memo + "압력 3 : " + Common.getInstance().valueConvert1(data.getSensorValue()) + "Bar ";
                    alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_yellow);
                    break;
                case "7":
                    wo_memo = wo_memo + "온도 NTC 1 : " + Common.getInstance().valueConvert(data.getSensorValue()) + "℃ ";
                    alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_yellow);
                    break;
                case "8":
                    wo_memo = wo_memo + "온도 PT100 : " + Common.getInstance().valueConvert(data.getSensorValue()) + "℃ ";
                    alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_yellow);
                    break;
                case "9":
                    wo_memo = wo_memo + "온도 NTC 2 : " + Common.getInstance().valueConvert(data.getSensorValue()) + "℃ ";
                    alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_yellow);
                    break;
                case "100":
                    wo_memo = "(기계 고장) 기계 한계값 초과";
                    alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_red);
                    break;
                case "300":
                    wo_memo = "(기계 고장) 인버터 전류 과부하 발생";
                    alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_red);
                    break;
                case "400":
                    wo_memo = "(기계 고장) 기계 전원 정전 발생";
                    alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_red);
                    break;
                case "500":
                    wo_memo = "(기계 고장) 메인모터 오버로드";
                    alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_red);
                    break;
                case "600":
                    wo_memo = "(기계 고장) 팬모터 오버로드";
                    alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_red);
                    break;
            }

            alarm_infoTV.setText(wo_memo);
            if (Integer.parseInt(data.getSensor()) >= 100) {
                alarm_monitoringLL.setVisibility(View.GONE);
                monitoring_chart_btnLL.setVisibility(View.VISIBLE);
            }
            if (data.getEngineerReadYn().equals("Y") && data.getCheckEngineer() == null)
                alarm_stateIV.setImageResource(R.drawable.icon_alarm_warning_gray);

            String mac = "MAC 없음", qr = "QR 코드 없음", complete_men = "완료자 없음";

            if (!isNullStr(data.getMcIotMac())) mac = data.getMcIotMac();
            if (!isNullStr(data.getQrCode())) qr = data.getQrCode();
            if (!isNullStr(data.getCheckEngineer())) {
                complete_men = data.getCheckEngineer() + " 완료";
                alarm_completeTV.setVisibility(View.GONE);
                alarm_stateIV.setImageResource(R.drawable.icon_alarm_check);
            }
            if (!isNullStr(data.getEngineerCheckMemo())) alarm_checked_memoET.setText(data.getEngineerCheckMemo());

            alarm_checked_memberTV.setText(complete_men);
            alarm_mc_qrTV.setText(qr);
            alarm_mc_iot_macTV.setText(mac);
            alarm_mc_airlineTV.setText(data.getMcAirline());
            alarm_cp_addrTV.setText(data.getCpAddr() + Common.getInstance().isNull(data.getCpAddrSub()));
        }

        boolean isNullStr(String str) {
            return TextUtils.isEmpty(str);
        }
    }
}
