package com.dbs.mplus.fatima.adapter;

import android.content.Context;
import android.content.Intent;
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.activity.ImageActivity;
import com.dbs.mplus.fatima.consent.ConsentFacade;
import com.dbs.mplus.fatima.consent.ConsentParameter;
import com.dbs.mplus.fatima.httpTask.DataParser;
import com.dbs.mplus.fatima.httpTask.HttpCon;
import com.dbs.mplus.fatima.model.ConsentImageListVO;
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 ConsentHistoryAdapter extends RecyclerView.Adapter<ConsentHistoryAdapter.ViewHolder> {

  private static final String TAG = "ConsentHistoryAdapter";
  private AppCompatActivity mActivity;

  private Context mContext;
  private ConsentActivity instance;
  public ArrayList<ConsentListVO> arrayList;

//  private String userId  = "";
//  private String userName = "";
  private String apiType = "";

  public HashMap<Integer, Object> checkMap;

  public ConsentHistoryAdapter(AppCompatActivity mActivity, Context mContext, ArrayList<ConsentListVO> arrayList, String apiType) {
    this.mActivity = mActivity;
    this.mContext  = mContext;
    this.arrayList = arrayList;
    this.instance  = (ConsentActivity) mContext;
//    this.userId    = Util.getStringPreference(mContext, "userInfo", "emplNo");
//    this.userName = Util.getStringPreference(mContext, "userInfo", "name");
    this.apiType  = apiType;

    this.checkMap = new HashMap<Integer, Object>();
  }

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

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

    public int position = 0;

    public ViewHolder(@NonNull View itemView) {
      super(itemView);
    }
  }

  @NonNull
  @Override
  public ConsentHistoryAdapter.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.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.chkConsent    = (CheckBox) view.findViewById(R.id.chkConsent);

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

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

    GradientDrawable tvSubBg = (GradientDrawable) holder.tvSubText.getBackground().getCurrent();
    holder.tvPatientName.setVisibility(View.GONE);

    GradientDrawable tvSubText = (GradientDrawable) holder.tvSubText.getBackground().getCurrent();
    if (consentState.equals(ConsentConfig.UNFINISHED)) {
      tvSubText.setColor(ContextCompat.getColor(mContext, R.color.alertColor));
    } else if (consentState.equals(ConsentConfig.TEMP) || consentState.equals(ConsentConfig.FNU_PRINT)) {
      tvSubText.setColor(ContextCompat.getColor(mContext, R.color.tempColor));
      if (consentState.equals(ConsentConfig.TEMP)) {
        consentStateDisp = mContext.getString(R.string.noWrite);
      } else {
        consentStateDisp = mContext.getString(R.string.fnuPrint);
      }
    } else if (consentState.equals(ConsentConfig.VERBAL)) {
      tvSubText.setColor(ContextCompat.getColor(mContext, R.color.vervbalColor));
    } else if (consentState.equals(ConsentConfig.ELECTR_CMP)) {
      tvSubText.setColor(ContextCompat.getColor(mContext, R.color.userDeptColor));
    } else if (consentState.equals(ConsentConfig.CERTIFY_CMP)) {
      tvSubText.setColor(ContextCompat.getColor(mContext, R.color.sexNAgeColor));
    } else if (consentState.equals(ConsentConfig.PAPER_OUT)) {
      tvSubText.setColor(ContextCompat.getColor(mContext, R.color.paperOutcolor));
    }

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

    holder.chkConsent.setOnCheckedChangeListener(onCheckedChangeListener);
    holder.listLayer.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();
      int position = holder.getLayoutPosition();
      ConsentListVO consentListVO = arrayList.get(position);
      String consentState = consentListVO.getConsentState();
      String consentMstRid = consentListVO.getConsentMstRid();
      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);

        if (consentState.equals(ConsentConfig.CERTIFY_CMP)) {

          notifyDataSetChanged();
          checkMap.clear();

          HashMap<String, String> mData = new HashMap<String, String>();
          mData.put("consentMstRid", consentMstRid);

          HttpCon con = new HttpCon(ConsentConfig.HOST_CONSENT, mData, ConsentConfig.GET_CONSENT_IMAGE);
          try {
            String result = con.execute().get();
            if (result.equals("")) {
              instance.csAlert.show();
              instance.csAlert.setContent(mContext.getString(R.string.imageLoadFailed), ConsentConfig.ALERT_BTN_TYPE);
              instance.csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                  instance.csAlert.dismiss();
                }
              });
            } else {
              ArrayList<ConsentImageListVO> arrayList = DataParser.getConsetImageList(mContext, result);
              if (arrayList.size() == 0) {
                instance.csAlert.show();
                instance.csAlert.setContent(mContext.getString(R.string.imageLoadFailed), ConsentConfig.ALERT_BTN_TYPE);
                instance.csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {
                    instance.csAlert.dismiss();
                  }
                });
              } else {
                Intent intent = new Intent(mContext, ImageActivity.class);
                intent.putExtra("imageArray", arrayList);
                instance.startActivity(intent);
              }
            }

          } catch (ExecutionException e) {
            e.printStackTrace();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }

          return;
        }

        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();
          String _consentStateDisp = _consentListVO.getConsentStateDisp();

          if (_consentState.equals(ConsentConfig.PAPER_OUT) || _consentState.equals(ConsentConfig.FNU_PRINT)) {
            printOnly.add("[" + _consentName + "] - " + _consentStateDisp);
          } else {
            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";
        }

        if (printOnlyAlertMsg.length() > 0) {
          instance.csAlert.show();
          instance.csAlert.setContent(mContext.getString(R.string.printOnlyConsent) + "\n" + 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();
              if (selectConsentList.size() > 0) {
                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, apiType, 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, apiType, certUserId);

        }

        notifyDataSetChanged();
        checkMap.clear();
      }

    }
  };

  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);
      }

    }
  };
}
