package com.dbs.mplus.knuh.adapter;

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

import com.dbs.mplus.knuh.BuildConfig;
import com.dbs.mplus.knuh.R;
import com.dbs.mplus.knuh.activity.ConsentActivity;
import com.dbs.mplus.knuh.consent.ConsentCreateParam;
import com.dbs.mplus.knuh.consent.ConsentEvent;
import com.dbs.mplus.knuh.consent.ConsentFacade;
import com.dbs.mplus.knuh.httpTask.CallBack;
import com.dbs.mplus.knuh.model.ConsentFormListVO;
import com.dbs.mplus.knuh.util.ConsentConfig;
import com.dbs.mplus.knuh.util.Util;

import java.util.ArrayList;
import java.util.HashMap;

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

import org.ksoap2.serialization.SoapObject;

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<ConsentFormListVO> arrayList;
  private ConsentEvent consentEvent;

  private String apiType = "";

  public ConsentListAdapter(AppCompatActivity mActivity, Context mContext, ArrayList<ConsentFormListVO> arrayList,  String apiType) {
    this.mActivity = mActivity;
    this.mContext  = mContext;
    this.instance  = (ConsentActivity) mContext;
    this.arrayList = arrayList;
    this.apiType   = apiType;
  }

  @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 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.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);
    return holder;
  }

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

    ConsentFormListVO consentFormListVO = arrayList.get(position);

    String formName = consentFormListVO.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.tvSubText.setText(subText);

    holder.listLayer.setOnClickListener(onClickListener);
    holder.tvSubText.setOnClickListener(onClickListener);

    holder.position = position;
  }

  private View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      ViewHolder holder = (ViewHolder) v.getTag();
      final int position = holder.getLayoutPosition();
      final ConsentFormListVO consentFormListVO = arrayList.get(position);
      String formCd          = consentFormListVO.getFormCd();
      String printOnly       = consentFormListVO.getPrintOnly();

      if (holder.listLayer == v) {
        if (instance.centerMenu.patientInfoVO == null) {
          instance.showSingButtonDialog(mContext.getString(R.string.emptyPatientInfo));
        } else {

          if (printOnly.equals("Y")) {
            instance.showSingButtonDialog(mContext.getString(R.string.printOnlyConsent));
          } else {
            CallBack callBack = new CallBack() {
              @Override
              public void result(final SoapObject result) {
                mActivity.runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                    String res = result.getProperty("responseData").toString().trim();
                    instance.dismissProgress();

                    if (res.equals("Y")) {
//                    instance.showSingButtonDialog(mContext.getString(R.string.toDayDupConsentMsg));
                      instance.csAlert.show();
                      instance.csAlert.setContent(mContext.getString(R.string.toDayDupConsentMsg), "");
                      instance.csAlert.btnConfirm.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                          instance.csAlert.dismiss();
                          consentEvent = new ConsentEvent(mContext, instance, consentFormListVO);
                          consentEvent.consentOpenProc(instance.centerMenu.patientInfoVO, "");
                        }
                      });
                      instance.csAlert.btnCancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                          instance.csAlert.dismiss();
                        }
                      });
                    } else {
                      consentEvent = new ConsentEvent(mContext, instance, consentFormListVO);
                      consentEvent.consentOpenProc(instance.centerMenu.patientInfoVO, "");
                    }
                  }
                });

              }

              @Override
              public void stop() {

              }

              @Override
              public void error() {

              }
            };

            instance.showProgress();
            HashMap<String, String> mData = new HashMap<String, String>();
            mData.put("instCd", BuildConfig.INST_CD);
            mData.put("pid", instance.centerMenu.patientInfoVO.getPid());
            mData.put("formCd", formCd);

            if (Util.checkNetwork(mContext) == true) {
              Util.callHttp(mContext, ConsentConfig.HOST_CONSENT, ConsentConfig.DUP_CERT_CONSENT, mData, callBack);
            } else {
              instance.dismissProgress();
              Util.networkErrorAlert(mActivity);
            }
          }

        }

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

        String soapAction = "";
        String alertMsg   = "";
        if (apiType.equals(ConsentConfig.GET_CONSENT_SEARCH)) {
          soapAction = ConsentConfig.SET_USER_FORM_SET;
          alertMsg = mContext.getString(R.string.addMaker);
        } else {
          soapAction = ConsentConfig.DEL_USER_FORM_SET;
          alertMsg = mContext.getString(R.string.deleteMaker);
        }

        instance.csAlert.show();
        instance.csAlert.setContent(alertMsg, "");
        final String finalSoapAction = soapAction;
        final String finalFormCd = formCd;
        instance.csAlert.btnConfirm.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            CallBack callBack = new CallBack() {
              @Override
              public void result(final SoapObject result) {
                Log.e(TAG, apiType + " result -- > " + result);
                mActivity.runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                    instance.dismissProgress();
                    if (result == null || result.toString().indexOf("null") > 0 || result.getPropertyCount() == 0) {
                      stop();
                    } else {
                      String rts = result.getProperty("responseData").toString().trim();
                      int res = Integer.parseInt(rts);

                      if (res == 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() {

              }
            };

            HashMap<String, String> mData = new HashMap<String, String>();
            mData.put("instCd", BuildConfig.INST_CD);
            mData.put("userId", Util.getStringPreference(mContext, "userInfo", "userId"));
            mData.put("formCd", finalFormCd);

            if (Util.checkNetwork(mContext) == true) {
              instance.showProgress();
              Util.callHttp(mContext, ConsentConfig.HOST_HOSPITAL, finalSoapAction, mData, callBack);
            } else {
              instance.dismissProgress();
              Util.networkErrorAlert(mActivity);
            }

            instance.csAlert.dismiss();
          }
        });

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

      }


    }
  };
}
