package com.dbs.mplus.fatima.adapter;

import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.dbs.mplus.fatima.R;
import com.dbs.mplus.fatima.activity.ConsentActivity;
import com.dbs.mplus.fatima.consent.ConsentFacade;
import com.dbs.mplus.fatima.consent.ConsentParameter;
import com.dbs.mplus.fatima.customView.CustomDeleteAlert;
import com.dbs.mplus.fatima.httpTask.HttpCallBack;
import com.dbs.mplus.fatima.httpTask.HttpCon;
import com.dbs.mplus.fatima.model.ConsentListVO;
import com.dbs.mplus.fatima.util.ConsentConfig;
import com.dbs.mplus.fatima.util.Util;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

public class ConsentTempAdapter extends RecyclerView.Adapter<ConsentTempAdapter.ViewHolder> {
  private static final String TAG = "ConsentTempAdapter";
  private AppCompatActivity mActivity;
  private Context mContext;
  private ConsentActivity instance;
  public ArrayList<ConsentListVO> arrayList;
//  private ConsentEvent consentEvent;
//  private String userId = "";
//  private String userName = "";

  public HashMap<Integer, Object> checkMap;

  private CustomDeleteAlert customDeleteAlert = null;

  public ConsentTempAdapter(AppCompatActivity mActivity, Context mContext, ArrayList<ConsentListVO> arrayList) {
    this.mActivity = mActivity;
    this.mContext  = mContext;
    this.instance  = (ConsentActivity) this.mContext;
    this.arrayList = arrayList;
//    this.userId    = Util.getStringPreference(mContext, "userInfo", "emplNo");
//    this.userName = Util.getStringPreference(mContext, "userInfo", "name");
    this.checkMap = new HashMap<Integer, Object>();
  }

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

  public class ViewHolder extends RecyclerView.ViewHolder {
    public RelativeLayout listLayer;
    public CheckBox chkConsent;
    public TextView tvConsentName;
    public TextView tvPatientName;
    public TextView tvTemp;
    public TextView tvSubText;

    public int position = 0;
    public ViewHolder(@NonNull View itemView) {
      super(itemView);
    }
  }

  @NonNull
  @Override
  public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.consent_list_item, parent, false);
    ViewHolder holder = new ViewHolder(view);

    holder.listLayer     = (RelativeLayout) view.findViewById(R.id.listLayer);
    holder.chkConsent    = (CheckBox) view.findViewById(R.id.chkConsent);
    holder.tvConsentName = (TextView) view.findViewById(R.id.tvConsentName);
    holder.tvPatientName = (TextView) view.findViewById(R.id.tvPatientName);
    holder.tvTemp        = (TextView) view.findViewById(R.id.tvTemp);
    holder.tvSubText     = (TextView) view.findViewById(R.id.tvSubText);

    holder.listLayer.setTag(holder);
    holder.tvSubText.setTag(holder);
    holder.chkConsent.setTag(holder);
    return holder;
  }

  @Override
  public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    ConsentListVO consentListVO = arrayList.get(position);
    String formName = consentListVO.getConsentName();
    String consentState = consentListVO.getConsentState();
    String consentStateDisp = consentListVO.getConsentStateDisp();

    holder.chkConsent.setVisibility(View.VISIBLE);

    GradientDrawable tvTempBg = (GradientDrawable) holder.tvTemp.getBackground().getCurrent();
    GradientDrawable tvSubBg = (GradientDrawable) holder.tvSubText.getBackground().getCurrent();

    if (consentState.equals(ConsentConfig.TEMP)) {
      tvTempBg.setColor(ContextCompat.getColor(mContext, R.color.tempColor));
      tvSubBg.setColor(ContextCompat.getColor(mContext, R.color.commonColor));
    } else if (consentState.equals(ConsentConfig.UNFINISHED)) {
      tvTempBg.setColor(ContextCompat.getColor(mContext, R.color.alertColor));
      tvSubBg.setColor(ContextCompat.getColor(mContext, R.color.commonColor));
    }

    holder.chkConsent.setChecked(false);
    holder.tvPatientName.setVisibility(View.GONE);
    holder.tvConsentName.setText(formName);
    holder.tvTemp.setText(consentStateDisp);

    holder.chkConsent.setOnCheckedChangeListener(onCheckedChangeListener);
    holder.listLayer.setOnClickListener(onClickListener);
    holder.tvSubText.setOnClickListener(onClickListener);

    if (checkMap.containsKey(holder.position) == true) {
      holder.chkConsent.setChecked(true);
    } else {
      holder.chkConsent.setChecked(false);
    }
  }

  private View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
      ViewHolder holder = (ViewHolder) view.getTag();
      final int position = holder.getLayoutPosition();
      ConsentListVO consentListVO = arrayList.get(position);
      final String formName = consentListVO.getConsentName();
      final String consentMstRid = consentListVO.getConsentMstRid();
      final String patientCode = consentListVO.getPatientCode();
      final String clnDeptCd = consentListVO.getClnDeptCd();
      final String ward = consentListVO.getWard();
      final String roomCd = consentListVO.getRoomCd();
      final String formRid = consentListVO.getFormRid();
      final String consentState = consentListVO.getConsentState();

      String certUserId = "";
      String certuserNm = "";
      if (holder.listLayer == view) {

        if (instance.mobile.equals("O")) {
          certUserId = instance.centerMenu.patientInfoVO.getMainDrId();
          certuserNm = instance.centerMenu.patientInfoVO.getMainDrNm();
        } else {
          certUserId = Util.getStringPreference(mContext, "userInfo", "emplNo");
          certuserNm = Util.getStringPreference(mContext, "userInfo", "name");
        }

        holder.chkConsent.setChecked(true);
        ArrayList<String> printOnly = new ArrayList<>();
        final ArrayList<ConsentListVO> selectConsentList = new ArrayList<>();
        for (int key : checkMap.keySet()) {
          ConsentListVO _consentListVO = arrayList.get(key);
          String _consentMstRid = _consentListVO.getConsentMstRid();
          String _consentState = _consentListVO.getConsentState();
          String _consentName = _consentListVO.getConsentName();

          HashMap<String, String> mData = new HashMap<String, String>();
          mData.put("consentmstrid", _consentMstRid);
          mData.put("consent_state", _consentState);

          HttpCon con = new HttpCon(ConsentConfig.HOST_CONSENT, mData, ConsentConfig.CHECK_CONSENT_STATE);
          try {
            String result = con.execute().get();
            if (!result.equals("")) {
              JSONObject object = Util.xmltoJsonObject(result);
              String res = Util.xmlToJsonString(object);
              ArrayList<HashMap<String, String>> mapArrayList = Util.parseJSON(mContext, res);

              String state = mapArrayList.get(0).get("CheckConsentStateResult");
              Log.e(TAG, "state -- > " + state);
              if (state.equals("-1")) {
                printOnly.add("[" + _consentName + "] - " + mContext.getString(R.string.stateFail));
              } else if (state.equals("1")) {
                printOnly.add("[" + _consentName + "] - " + mContext.getString(R.string.writeConsent));
              } else if (state.equals("0")) {
                selectConsentList.add(_consentListVO);
              }
            }
          } catch (ExecutionException e) {
            e.printStackTrace();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }

        String printOnlyAlertMsg = "";
        if (printOnly.size() > 0) {
          printOnlyAlertMsg = printOnly.get(printOnly.size() - 1) + "\n" + mContext.getString(R.string.printOnlyConsent);
        }

        if (printOnlyAlertMsg.length() > 0) {
          instance.csAlert.show();
          instance.csAlert.setContent(printOnlyAlertMsg, "");
          final String finalCertUserId = certUserId;
          final String finalCertuserNm = certuserNm;
          instance.csAlert.btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              instance.csAlert.dismiss();
              HashMap<String, Object> param = new HashMap<String, Object>();
              HashMap<String, String> globalParam = new HashMap<String, String>();
              ArrayList<HashMap<String, Object>> consentParam = new ArrayList<HashMap<String, Object>>();
              globalParam = ConsentParameter.makeGlobalParam(instance.centerMenu.patientInfoVO, finalCertUserId, mContext);
              consentParam = ConsentParameter.makeConsent(instance.centerMenu.patientInfoVO, selectConsentList, finalCertuserNm, "patient", mContext);

              param.put("globalParam", globalParam);
              param.put("consentParam", consentParam);

              ConsentFacade consentFacade = new ConsentFacade(mContext);
              consentFacade.startConsent(param, "centerTemp", finalCertUserId);
            }
          });
          instance.csAlert.btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              instance.csAlert.dismiss();
            }
          });
        } else {
          HashMap<String, Object> param = new HashMap<String, Object>();
          HashMap<String, String> globalParam = new HashMap<String, String>();
          ArrayList<HashMap<String, Object>> consentParam = new ArrayList<HashMap<String, Object>>();
          globalParam = ConsentParameter.makeGlobalParam(instance.centerMenu.patientInfoVO, certUserId, mContext);
          consentParam = ConsentParameter.makeConsent(instance.centerMenu.patientInfoVO, selectConsentList, certuserNm, "patient", mContext);

          param.put("globalParam", globalParam);
          param.put("consentParam", consentParam);

          ConsentFacade consentFacade = new ConsentFacade(mContext);
          consentFacade.startConsent(param, "centerTemp", certUserId);
        }

        notifyDataSetChanged();
        checkMap.clear();

      } else if (holder.tvSubText == view) {
        instance.csAlert.show();
        instance.csAlert.setContent(mContext.getString(R.string.deleteConsent), "");
        instance.csAlert.btnConfirm.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            instance.csAlert.dismiss();
            HttpCallBack callBack = new HttpCallBack() {
              @Override
              public void result(final String result) {
                instance.runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                    instance.dismissProgress();
                    if (result.equals("")) {
                      stop();
                    } else {
                      JSONObject object = Util.xmltoJsonObject(result);
                      String res = Util.xmlToJsonString(object);
                      ArrayList<HashMap<String, String>> mapArrayList = Util.parseJSON(mContext, res);
                      Log.e(TAG, "mapArrayList -- > " + mapArrayList);
                      int rts = Integer.parseInt(mapArrayList.get(0).get("SaveDeleteResult").trim());
//                      int rts = Integer.parseInt(res);

                      if (rts > 0) {
                        customDeleteAlert.dismiss();
                      } else {
                        stop();
                      }
                    }

                    arrayList.remove(position);
                    notifyItemRemoved(position);

                  }
                });
              }

              @Override
              public void stop() {
                String message = String.format(mContext.getString(R.string.deleteConsentFailed), formName);
                ((ConsentActivity) mContext).showSingButtonDialog(message);
              }

              @Override
              public void error() {

              }
            };

            String userId = Util.getStringPreference(mContext, "userInfo", "emplNo");

            HashMap<String, String> mData = new HashMap<String, String>();
            mData.put("userId", userId);
            mData.put("consentMstRidInt", consentMstRid);
            mData.put("patientCode", patientCode);
            mData.put("clnDeptCode", clnDeptCd);
            mData.put("ward", ward);
            mData.put("roomcd", roomCd);
            mData.put("formRid", formRid);
//            mData.put("rewriteConsentMstRid", "0");
            mData.put("reissueConsentMstRid", "1");
            mData.put("consentState", consentState);
            mData.put("deviceIdentNo", "");

            customDeleteAlert = new CustomDeleteAlert(mContext, mData, callBack);
            customDeleteAlert.show();
          }
        });
        instance.csAlert.btnCancel.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            instance.csAlert.dismiss();
          }
        });
      }

    }
  };

  private CheckBox.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
      ViewHolder holder = (ViewHolder) buttonView.getTag();
      final int position = holder.getLayoutPosition();
      ConsentListVO consentListVO = arrayList.get(position);
      String consentMstRid = consentListVO.getConsentMstRid();

      Log.e(TAG, "position -- > " + position);
      Log.e(TAG, "isChecked -- > " + isChecked);
      if (isChecked == true) {
        checkMap.put(position, consentMstRid);
      } else {
        checkMap.remove(position);
      }

    }
  };
}
