package com.dbs.mplus.fatima.adapter;

import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import android.util.Log;
import android.util.SparseBooleanArray;
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.httpTask.HttpCallBack;
import com.dbs.mplus.fatima.model.ConsentSetListVO;
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;

public class ConsentListAdapter extends RecyclerView.Adapter<ConsentListAdapter.ViewHolder> {

  private static final String TAG = "ConsentListAdapter";
  private AppCompatActivity mActivity;
  private Context mContext;
  private ConsentActivity instance;
  public ArrayList arrayList;
//  private ConsentEvent consentEvent;

  private String apiType = "";
//  private String userId = "";
//  private String userName = "";
  public HashMap<Integer, Object> checkMap;
  private SparseBooleanArray array = new SparseBooleanArray();

  public ConsentListAdapter(AppCompatActivity mActivity, Context mContext, ArrayList arrayList, String apiType) {
    this.mActivity = mActivity;
    this.mContext  = mContext;
    this.instance  = (ConsentActivity) mContext;
    this.arrayList = arrayList;
    this.apiType   = apiType;
//    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);

    GradientDrawable tvSubBg = (GradientDrawable) holder.tvSubText.getBackground().getCurrent();
    tvSubBg.setColor(ContextCompat.getColor(mActivity, R.color.typeRightColor));

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

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

    ConsentSetListVO consentSetListVO = (ConsentSetListVO) arrayList.get(position);

    String formName = consentSetListVO.getFormName();
    holder.tvConsentName.setText(formName);

    holder.tvPatientName.setVisibility(View.GONE);
    holder.tvTemp.setVisibility(View.GONE);
//    holder.tvSubText.setText(R.string.add);

    String subText = "";
    if (apiType.equals(ConsentConfig.GET_CONSENT_SET_LIST)) {
      subText = mContext.getString(R.string.delete);
    } else if (apiType.equals(ConsentConfig.GET_CONSENT_SEARCH)) {
      subText = mContext.getString(R.string.add);
    }

    holder.chkConsent.setVisibility(View.VISIBLE);
    holder.tvSubText.setText(subText);

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

    holder.position = position;

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

//    if (array.get(position)) {
//      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();
      ConsentSetListVO consentSetListVO = (ConsentSetListVO) arrayList.get(position);
      final String fromCd  = consentSetListVO.getFormCd();
      String certUserId = "";
      String certuserNm = "";

      if (view == holder.listLayer) {
        if (instance.centerMenu.patientInfoVO == null) {
          instance.csAlert.show();
          instance.csAlert.setContent(mContext.getString(R.string.emptyPatientInfo), ConsentConfig.ALERT_BTN_TYPE);
          instance.csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              instance.csAlert.dismiss();
            }
          });
        } else {

          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<ConsentSetListVO> printOnly = new ArrayList<>();
          final ArrayList<ConsentSetListVO> selectConsentList = new ArrayList<>();
          for (int key : checkMap.keySet()) {
            ConsentSetListVO _consentSetListVO = (ConsentSetListVO) arrayList.get(key);
            String _printOnly = _consentSetListVO.getPrintOnly().toUpperCase().trim();
            if (_printOnly.equals("Y")) {
              printOnly.add(_consentSetListVO);
            } else {
              selectConsentList.add(_consentSetListVO);
            }
          }

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

          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();
                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.makeNewConsentParam(instance.centerMenu.patientInfoVO, selectConsentList, finalCertuserNm, 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.makeNewConsentParam(instance.centerMenu.patientInfoVO, selectConsentList, certuserNm, mContext);

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

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

        notifyDataSetChanged();
        checkMap.clear();

      } else if (view == holder.tvSubText) {

        String msg = "";
        if (apiType.equals(ConsentConfig.GET_CONSENT_SET_LIST)) {
          msg = mContext.getString(R.string.deleteMaker);
        } else {
          msg = mContext.getString(R.string.addMaker);
        }
        instance.csAlert.show();
        instance.csAlert.setContent(msg, "");
        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) {
                Log.e(TAG, "result -- > " + result);
                mActivity.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);
                      String rts = mapArrayList.get(0).get("responseData");
                      if (rts.equals("0")) {
                        stop();
                      } else {
                        if (apiType.equals(ConsentConfig.GET_CONSENT_SET_LIST)) {
                          arrayList.remove(position);
                          notifyItemRemoved(position);
                        }
                      }
                    }

                  }
                });

              }

              @Override
              public void stop() {
                String message = "";
                if (apiType.equals(ConsentConfig.GET_CONSENT_SEARCH)) {
                  message = String.format(mContext.getString(R.string.failMakerEvent), mContext.getString(R.string.add));
                } else {
                  message= String.format(mContext.getString(R.string.failMakerEvent), mContext.getString(R.string.delete));
                }
                instance.showSingButtonDialog(message);
              }

              @Override
              public void error() {

              }
            };

            String method = "";
            HashMap<String, String> mData = new HashMap<String, String>();
            if (apiType.equals(ConsentConfig.GET_CONSENT_SET_LIST)) {
              method = ConsentConfig.DEL_USER_FORM_SET_LIST;
            } else {
              method = ConsentConfig.SET_USER_FORM_SET_LIST;
            }

            String userId = Util.getStringPreference(mContext, "userInfo", "emplNo");
            mData.put("userid", userId);
            mData.put("formcd", fromCd);
            if (Util.checkNetwork(mContext) == true) {
              instance.showProgress();
              Util.callHttp(mContext, ConsentConfig.HOST_HOSPITAL, method, mData, callBack);
            } else {
              instance.dismissProgress();
              Util.networkErrorAlert(mActivity);
            }
          }
        });

        instance.csAlert.btnCancel.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            instance.csAlert.dismiss();
          }
        });
      }

    }
  };

  private View.OnClickListener checkOnClick = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
      ViewHolder holder = (ViewHolder) view.getTag();
      final int position = holder.getLayoutPosition();
      ConsentSetListVO consentSetListVO = (ConsentSetListVO) arrayList.get(position);
      String formRid = consentSetListVO.getFormRid();

      if (holder.chkConsent.isChecked() == true) {
        array.put(position, true);
        checkMap.put(position, formRid);
      } else {
        array.put(position, false);
        checkMap.remove(position);
      }

      notifyDataSetChanged();
    }
  };

  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();
      ConsentSetListVO consentSetListVO = (ConsentSetListVO) arrayList.get(position);
      String formRid = consentSetListVO.getFormRid();

      if (isChecked == true) {
        checkMap.put(position, formRid);
      } else {
        checkMap.remove(position);
      }
    }
  };
}
