package kr.co.compcarecompany.Util.Adapter;

import android.content.Context;
import android.os.Handler;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
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.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.Product.ReportData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.CustomView.AlarmListDialog;
import kr.co.compcarecompany.Util.CustomView.ReportModifyDialog;
import kr.co.compcarecompany.Util.CustomView.ServiceDetailDialog;

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

    private ArrayList<ReportData> items = new ArrayList<>();
    private Context context;
    private Handler handler;
    private ReportImageAdapter2 photo_adapter;
    private FragmentActivity fa;

    private MachineManagementReportContentAdapter.OnLoadMoreListener OnLoadMoreListener;

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

    private MachineManagementReportContentAdapter.OnReportListener OnReportListener;

    public interface OnReportListener {
        void onClick(int position);
    }

    private MachineManagementReportContentAdapter.OnAlarmListener OnAlarmListener;

    public interface OnAlarmListener {
        void onClick(int position);
    }

    public MachineManagementReportContentAdapter(Context context, Handler handler, MachineManagementReportContentAdapter.OnLoadMoreListener OnLoadMoreListener,
                                                 MachineManagementReportContentAdapter.OnReportListener OnReportListener, MachineManagementReportContentAdapter.OnAlarmListener OnAlarmListener,
                                                 FragmentActivity fa) {
        this.context = context;
        this.handler = handler;
        this.OnLoadMoreListener = OnLoadMoreListener;
        this.OnReportListener = OnReportListener;
        this.OnAlarmListener = OnAlarmListener;
        this.fa = fa;
    }

    @NonNull
    @Override
    public MachineManagementReportContentAdapter.ItemViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_alarm_report_content, viewGroup, false);
        return new MachineManagementReportContentAdapter.ItemViewHolder(v);
    }

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

        try {
            itemViewHolder.onBind(items.get(position));
        } catch (ParseException e) {
            e.printStackTrace();
        }

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


        int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6f, context.getResources().getDisplayMetrics());
        photo_adapter = new ReportImageAdapter2(context, 30 * px);

        if (items.get(position).getArIdx() != null) {
            if (items.get(position).getPhotoList() != null && items.get(position).getPhotoList().size() > 0) {
                itemViewHolder.report_photoLL.setVisibility(View.VISIBLE);
                itemViewHolder.report_photoRV.setAdapter(photo_adapter);

                String manager_uri = "https://www.compcare.co.kr/uploads/alarm_report/";
                ArrayList<String> photo_uri = new ArrayList<>();

                for (int i = 0; i < items.get(position).getPhotoList().size(); i++) {
                    photo_uri.add(manager_uri + items.get(position).getPhotoList().get(i).getPfiFilename());
                }
                photo_adapter.addItem(photo_uri);

            } else {
                itemViewHolder.report_photoLL.setVisibility(View.GONE);
            }

        } else {

            if (items.get(position).getPhotoList() != null && items.get(position).getPhotoList().size() > 0) {
                itemViewHolder.report_photoLL.setVisibility(View.VISIBLE);
                itemViewHolder.report_photoRV.setAdapter(photo_adapter);

                String manager_uri = "https://www.compcare.co.kr/uploads/work/";
                ArrayList<String> photo_uri = new ArrayList<>();

                int size = items.get(position).getPhotoList().size();
                if (items.get(position).getPhotoList().size() > 4) size = 4;
                for (int i = 0; i < size; i++) {
                    photo_uri.add(manager_uri + items.get(position).getPhotoList().get(i).getPfiFilename());
                }
                photo_adapter.addItem(photo_uri);

            } else {
                itemViewHolder.report_photoLL.setVisibility(View.GONE);
            }

        }

        itemViewHolder.alarm_listIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (items.get(position).getArIdx() != null) {
                    AlarmListDialog dialog = new AlarmListDialog(context, handler, items.get(position).getArIdx(), null, items.get(position).getCpIdx(), items.get(position).getMcIotMac(), "report");
                    dialog.show();

                } else {

                    AlarmListDialog dialog = new AlarmListDialog(context, handler, null, items.get(position).getWo_idx(), items.get(position).getCpIdx(), items.get(position).getMcIotMac(), "work");
                    dialog.show();
                }
            }
        });

        itemViewHolder.reportIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (items.get(position).getArIdx() != null) {
                    //작업일지 가져오기
                    ReportModifyDialog dialog = new ReportModifyDialog(context, handler, items.get(position).getArIdx(), fa.userItem.getArrayitem().getPtIdx(), fa.userItem.getArrayitem().getAgIdx(),
                            fa.userItem.getArrayitem().getMbId(), fa);
                    dialog.show();

                } else {
                    //서비스 레포트 가져오기
                    ServiceDetailDialog dialog = new ServiceDetailDialog(context, handler, items.get(position).getWo_idx());
                    dialog.show();
                }
            }
        });
    }

    @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<ReportData> data) {

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

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

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

    static class ItemViewHolder extends RecyclerView.ViewHolder {

        //작업일지
        TextView pd_nameTV, mc_lotTV, work_dateTV, work_memoTV, report_memoTV;
        ImageView reportIV, alarm_listIV;
        RecyclerView report_photoRV;
        LinearLayout report_photoLL;

        ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            pd_nameTV = itemView.findViewById(R.id.pd_nameTV);
            mc_lotTV = itemView.findViewById(R.id.mc_lotTV);
            work_dateTV = itemView.findViewById(R.id.work_dateTV);
            work_memoTV = itemView.findViewById(R.id.work_memoTV);
//            report_memoTV = itemView.findViewById(R.id.report_memoTV);
            reportIV = itemView.findViewById(R.id.reportIV);
            alarm_listIV = itemView.findViewById(R.id.alarm_listIV);
            report_photoRV = itemView.findViewById(R.id.report_photoRV);
            report_photoLL = itemView.findViewById(R.id.report_photoLL);

        }

        void onBind(ReportData data) throws ParseException {
            pd_nameTV.setText(data.getPdName());
            if (data.getMcLot() != null) mc_lotTV.setText(data.getMcLot());

            //점검일지 일때
            if (data.getArIdx() != null) {
                work_dateTV.setText(data.getArWorkDate());

                String wo_memo = "(주의) ";

                for (int i = 0; i < data.getSensorArr().size(); i++) {

                    switch (data.getSensorArr().get(i).getSensor()) {
                        case "1":
                            wo_memo = wo_memo + "전류 1 : " + data.getSensorArr().get(i).getMaxSensorValue() + "A 초과";
                            break;
                        case "2":
                            if (!wo_memo.equals(("(주의) "))) wo_memo = wo_memo + "/ ";
                            wo_memo = wo_memo + "전류 2 : " + data.getSensorArr().get(i).getMaxSensorValue() + "A 초과";
                            break;
                        case "3":
                            if (!wo_memo.equals(("(주의) "))) wo_memo = wo_memo + "/ ";
                            wo_memo = wo_memo + "전류 3 : " + data.getSensorArr().get(i).getMaxSensorValue() + "A 초과";
                            break;
                        case "4":
                            if (!wo_memo.equals(("(주의) "))) wo_memo = wo_memo + "/ ";
                            wo_memo = wo_memo + "압력 1 : " + Common.getInstance().valueConvert1(data.getSensorArr().get(i).getMaxSensorValue()) + "Bar 초과";
                            break;
                        case "5":
                            if (!wo_memo.equals(("(주의) "))) wo_memo = wo_memo + "/ ";
                            wo_memo = wo_memo + "압력 2 : " + Common.getInstance().valueConvert1(data.getSensorArr().get(i).getMaxSensorValue()) + "Bar 초과";
                            break;
                        case "6":
                            if (!wo_memo.equals(("(주의) "))) wo_memo = wo_memo + "/ ";
                            wo_memo = wo_memo + "압력 3 : " + Common.getInstance().valueConvert1(data.getSensorArr().get(i).getMaxSensorValue()) + "Bar 초과";
                            break;
                        case "7":
                            if (!wo_memo.equals(("(주의) "))) wo_memo = wo_memo + "/ ";
                            wo_memo = wo_memo + "온도 NTC 1 : " + data.getSensorArr().get(i).getMaxSensorValue() + "℃ 초과";
                            break;
                        case "8":
                            if (!wo_memo.equals(("(주의) "))) wo_memo = wo_memo + "/ ";
                            wo_memo = wo_memo + "온도 PT100 : " + data.getSensorArr().get(i).getMaxSensorValue() + "℃ 초과";
                            break;
                        case "9":
                            if (!wo_memo.equals(("(주의) "))) wo_memo = wo_memo + "/ ";
                            wo_memo = wo_memo + "온도 NTC 2 : " + data.getSensorArr().get(i).getMaxSensorValue() + "℃ 초과";
                            break;
                        case "10":
                            if (!wo_memo.equals(("(주의) "))) wo_memo = wo_memo + "/ ";
                            wo_memo = wo_memo + "압력 1 : " + Common.getInstance().valueConvert1(data.getSensorArr().get(i).getMaxSensorValue()) + "Bar 미만";
                            break;
                        case "11":
                            if (!wo_memo.equals(("(주의) "))) wo_memo = wo_memo + "/ ";
                            wo_memo = wo_memo + "압력 2 : " + Common.getInstance().valueConvert1(data.getSensorArr().get(i).getMaxSensorValue()) + "Bar 미만";
                            break;
                        case "12":
                            if (!wo_memo.equals(("(주의) "))) wo_memo = wo_memo + "/ ";
                            wo_memo = wo_memo + "압력 3 : " + Common.getInstance().valueConvert1(data.getSensorArr().get(i).getMaxSensorValue()) + "Bar 미만";
                            break;
                    }
                }
                work_memoTV.setText(wo_memo);

                //서비스 레포트 일때
            } else {

                if (data.getWrEnddt() != null) {
                    SimpleDateFormat beforeSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date beforeDate = beforeSDF.parse(data.getWrEnddt());
                    SimpleDateFormat afterSDF = new SimpleDateFormat("yyyy.MM.dd");
                    String afterDate = afterSDF.format(beforeDate);
                    work_dateTV.setText(afterDate);
                }

                String wo_memo = "";

                switch (data.getSensor()) {
                    case "100":
                        wo_memo = "(기계 고장) 기계 한계값 초과";
                        break;
                    case "300":
                        wo_memo = "(기계 고장) 인버터 전류 과부하 발생";
                        break;
                    case "400":
                        wo_memo = "(기계 고장) 기계 전원 정전 발생";
                        break;
                    case "500":
                        wo_memo = "(기계 고장) 메인모터 오버로드";
                        break;
                    case "600":
                        wo_memo = "(기계 고장) 팬모터 오버로드";
                        break;
                }

                work_memoTV.setText(wo_memo);

            }
        }
    }
}
