package kr.co.compcarecompany.Util.Adapter;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

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

import java.util.ArrayList;

import kr.co.compcarecompany.Data.Product.AlarmData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.MyOnItemClick;

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

    Context context;
    Handler handler;
    MyOnItemClick callback;
    //작업일지 보기 클릭 리스너
    private MachineAlarmAdapter.reportListener reportListener;

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

    private ArrayList<AlarmData> items = new ArrayList<>();

    public MachineAlarmAdapter(@NonNull Context context, MyOnItemClick callback, MachineAlarmAdapter.reportListener reportListener) {
        this.context = context;
        this.callback = callback;
        this.reportListener = reportListener;
    }

    @NonNull
    @Override
    public MachineAlarmAdapter.ItemViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_machine_alarm, viewGroup, false);

        return new MachineAlarmAdapter.ItemViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull MachineAlarmAdapter.ItemViewHolder itemViewHolder, int position) {

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

        itemViewHolder.item_alarm_stopTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Bundle bundle = new Bundle();
                bundle.putString("mcl_idx", items.get(position).getMclIdx());
                bundle.putString("mac", items.get(position).getMcIotMac());
                bundle.putString("msg", items.get(position).getSensor());
                callback.onClick(bundle);
            }
        });

        itemViewHolder.alarmCB.setOnCheckedChangeListener(null);
        itemViewHolder.alarmCB.setChecked(items.get(position).isChecked());

        itemViewHolder.alarmCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                items.get(position).setChecked(isChecked);
            }
        });

        itemViewHolder.report_statusTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("mcl_idx", items.get(position).getMclIdx());
                bundle.putString("ar_idx", items.get(position).getArIdx());
                bundle.putString("sensor", items.get(position).getSensor());
                bundle.putString("report_yn", items.get(position).getReportYn());
                reportListener.clickBtn(bundle);
            }
        });
    }

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

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

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

    public void addItem(ArrayList<AlarmData> data) {

        // 외부에서 item을 추가시킬 함수입니다.
        items.clear();
        items.addAll(data);
        notifyDataSetChanged();
    }

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

    static class ItemViewHolder extends RecyclerView.ViewHolder {

        TextView item_alarm_macTV, item_alarm_typeTV, item_push_timeTV, item_alarm_stopTV, item_alarm_delayTV, item_alarm_valueTV,
                report_statusTV, report_writeTV, item_alarm_informTV, item_machine_nameTV, item_read_timeTV, item_check_listTV, item_alarm_qrTV;
        CheckBox alarmCB;
        LinearLayout item_btnLL, item_read_timeLL, item_check_listLL;

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

            alarmCB = itemView.findViewById(R.id.alarmCB);
            item_alarm_macTV = itemView.findViewById(R.id.item_alarm_macTV);
            item_alarm_typeTV = itemView.findViewById(R.id.item_alarm_typeTV);
            item_push_timeTV = itemView.findViewById(R.id.item_push_timeTV);
            item_alarm_stopTV = itemView.findViewById(R.id.item_alarm_stopTV);
            item_alarm_delayTV = itemView.findViewById(R.id.item_alarm_delayTV);
            item_alarm_valueTV = itemView.findViewById(R.id.item_alarm_valueTV);
            report_statusTV = itemView.findViewById(R.id.report_statusTV);
            item_alarm_informTV = itemView.findViewById(R.id.item_alarm_informTV);
            item_machine_nameTV = itemView.findViewById(R.id.item_machine_nameTV);
            item_read_timeTV = itemView.findViewById(R.id.item_read_timeTV);
            item_read_timeLL = itemView.findViewById(R.id.item_read_timeLL);
            item_check_listTV = itemView.findViewById(R.id.item_check_listTV);
            item_check_listLL = itemView.findViewById(R.id.item_check_listLL);
            item_btnLL = itemView.findViewById(R.id.item_btnLL);
            item_alarm_qrTV = itemView.findViewById(R.id.item_alarm_qrTV);

        }

        void onBind(AlarmData data) {

            item_push_timeTV.setText(data.getPushDt());

            if (data.getReadYn().equals("Y")) {
                item_alarm_stopTV.setVisibility(View.GONE);
            }

            if (data.getReportYn().equals("Y")) {
                report_statusTV.setVisibility(View.VISIBLE);
                alarmCB.setVisibility(View.GONE);

            } else {
                report_statusTV.setVisibility(View.GONE);
                alarmCB.setVisibility(View.VISIBLE);
            }

            if(data.getMachineData().getMcIotMac() != null && !data.getMachineData().getMcIotMac().equals("") ) {
                item_alarm_macTV.setText(data.getMachineData().getMcIotMac());
            }

            if(data.getMachineData().getQrCode() != null && !data.getMachineData().getQrCode().equals("") ) {
                item_alarm_qrTV.setText(data.getMachineData().getQrCode().toString());
            }

            if(data.getMachineData().getPdName() != null){
                item_machine_nameTV.setText(data.getMachineData().getPdName());
            }

            String type;
            String unit;
            float up;
            float down;
            String warn;
            switch (data.getSensor()) {
                case "0":
                    type = "IoT 재시작";
                    unit = "";
                    alarmCB.setEnabled(false);
                    item_alarm_valueTV.setVisibility(View.GONE);
                    item_alarm_stopTV.setVisibility(View.GONE);
                    item_check_listLL.setVisibility(View.GONE);
                    report_statusTV.setVisibility(View.VISIBLE);
                    item_btnLL.setVisibility(View.GONE);
                    if(data.getReportYn().equals("N")){
                        report_statusTV.setText("작업일지 작성");
                    }
                    break;
                case "1":
                    type = "전류1";
                    unit = " A";
                    up = Float.parseFloat(data.getMachineData().getMcCurrent1Up());
                    down = Float.parseFloat(data.getMachineData().getMcCurrent1Down());
                    item_check_listTV.setText("마그넷트 접촉 체크, 차단기 전선 체크, 모터저항이 높아짐");
                    warn = "전류";
                    break;
                case "2":
                    type = "전류2";
                    unit = " A";
                    up = Float.parseFloat(data.getMachineData().getMcCurrent2Up());
                    down = Float.parseFloat(data.getMachineData().getMcCurrent2Down());
                    item_check_listTV.setText("마그넷트 접촉 체크, 차단기 전선 체크, 모터저항이 높아짐");
                    warn = "전류";
                    break;
                case "3":
                    type = "전류3";
                    unit = " A";
                    up = Float.parseFloat(data.getMachineData().getMcCurrent3Up());
                    down = Float.parseFloat(data.getMachineData().getMcCurrent3Down());
                    item_check_listTV.setText("마그넷트 접촉 체크, 차단기 전선 체크, 모터저항이 높아짐");
                    warn = "전류";
                    break;
                case "4":
                    type = "압력1";
                    unit = " Bar";
                    up = Float.parseFloat(data.getMachineData().getMcPressure1Up());
                    down = Float.parseFloat(data.getMachineData().getMcPressure1Down());
                    item_check_listTV.setText("토출밸브 체크, 토출밸브 막힘 확인");
                    warn = "압력";
                    break;
                case "5":
                    type = "압력2";
                    unit = " Bar";
                    up = Float.parseFloat(data.getMachineData().getMcPressure2Up());
                    down = Float.parseFloat(data.getMachineData().getMcPressure2Down());
                    item_check_listTV.setText("토출밸브 체크, 토출밸브 막힘 확인");
                    warn = "압력";
                    break;
                case "6":
                    type = "압력3";
                    unit = " Bar";
                    up = Float.parseFloat(data.getMachineData().getMcPressure3Up());
                    down = Float.parseFloat(data.getMachineData().getMcPressure3Down());
                    item_check_listTV.setText("토출밸브 체크, 토출밸브 막힘 확인");
                    warn = "압력";
                    break;
                case "7":
                    type = "온도NTC";
                    unit = " ℃";
                    up = Float.parseFloat(data.getMachineData().getMcTempNtcUp());
                    down = Float.parseFloat(data.getMachineData().getMcTempNtcDown());
                    item_check_listTV.setText("오일량 체크, 쿨러먼지 청소 확인");
                    warn = "온도";
                    break;
                case "8":
                    type = "온도PT100";
                    unit = " ℃";
                    up = Float.parseFloat(data.getMachineData().getMcTempPtUp());
                    down = Float.parseFloat(data.getMachineData().getMcTempPtDown());
                    item_check_listTV.setText("오일량 체크, 쿨러먼지 청소 확인");
                    warn = "온도";
                    break;
                case "9":
                    type = "온도NTC_2";
                    unit = " ℃";
                    up = Float.parseFloat(data.getMachineData().getMcTempNtc2Up());
                    down = Float.parseFloat(data.getMachineData().getMcTempNtc2Down());
                    item_check_listTV.setText("오일량 체크, 쿨러먼지 청소 확인");
                    warn = "온도";
                    break;

                case "100":
                    type = "기계 한계값 초과로 서비스 접수";
                    unit = "";
                    alarmCB.setEnabled(false);
                    item_alarm_valueTV.setVisibility(View.GONE);
                    item_alarm_stopTV.setVisibility(View.GONE);
                    item_check_listLL.setVisibility(View.GONE);
                    item_btnLL.setVisibility(View.GONE);
                    break;
                case "200":
                    type = "소모품 만료";
                    unit = "";
                    alarmCB.setEnabled(false);
                    item_alarm_valueTV.setVisibility(View.GONE);
                    item_alarm_stopTV.setVisibility(View.GONE);
                    item_check_listLL.setVisibility(View.GONE);
                    item_btnLL.setVisibility(View.GONE);
                    break;
                case "300":
                    type = "메인 모터 과부하로 서비스 접수";
                    unit = "";
                    alarmCB.setEnabled(false);
                    item_alarm_valueTV.setVisibility(View.GONE);
                    item_alarm_stopTV.setVisibility(View.GONE);
                    item_check_listLL.setVisibility(View.GONE);
                    item_btnLL.setVisibility(View.GONE);
                    break;
                case "400":
                    type = "메인 3상 전원 차단으로 서비스 접수";
                    unit = "";
                    alarmCB.setEnabled(false);
                    item_alarm_valueTV.setVisibility(View.GONE);
                    item_alarm_stopTV.setVisibility(View.GONE);
                    item_check_listLL.setVisibility(View.GONE);
                    item_btnLL.setVisibility(View.GONE);
                    break;
                case "500":
                    type = "메인모터 오버로드";
                    unit = "";
                    alarmCB.setEnabled(false);
                    item_alarm_valueTV.setVisibility(View.GONE);
                    item_alarm_stopTV.setVisibility(View.GONE);
                    item_check_listLL.setVisibility(View.GONE);
                    item_btnLL.setVisibility(View.GONE);
                    break;
                case "600":
                    type = "팬모터 오버로드";
                    unit = "";
                    alarmCB.setEnabled(false);
                    item_alarm_valueTV.setVisibility(View.GONE);
                    item_alarm_stopTV.setVisibility(View.GONE);
                    item_check_listLL.setVisibility(View.GONE);
                    item_btnLL.setVisibility(View.GONE);
                    break;
                default:
                    type = data.getSensor();
                    unit = "";
                    item_check_listTV.setText("미확인 알람");
                    warn = "";
                    break;
            }

            item_alarm_typeTV.setText(type);
            item_alarm_valueTV.setText(Common.getInstance().valueConvert1(Common.getInstance().isNullToZero(data.getSensorValue())) + unit);

            if (data.getDelayTime() != null && !data.getDelayTime().equals("")) {
                int delay_time = Integer.parseInt(data.getDelayTime()) / 60;
                item_alarm_delayTV.setText(delay_time + " 분 후 재알림");
            }

            if (data.getReadTime() != null && !data.getReadTime().equals("")) {
                item_read_timeLL.setVisibility(View.VISIBLE);
                item_read_timeTV.setText(data.getReadTime());
            }
//            if(Integer.parseInt(data.getSensorValue()) > up){
//                item_alarm_informTV.setText(warn+" 상승함");
//
//            } else if (Integer.parseInt(data.getSensorValue()) < down){
//                item_alarm_informTV.setText(warn+" 하강함");
//            }
        }
    }
}
