package com.dbs.consent.demo.adapter;

import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
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 androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.dbs.consent.demo.BuildConfig;
import com.dbs.consent.demo.R;
import com.dbs.consent.demo.activity.ConsentActivity;
import com.dbs.consent.demo.consent.ConsentEvent;
import com.dbs.consent.demo.customView.CustomDeleteAlert;
import com.dbs.consent.demo.httpTask.CallBack;
import com.dbs.consent.demo.httpTask.SoapParser;
import com.dbs.consent.demo.model.ConsentFormListVO;
import com.dbs.consent.demo.model.PatientInfoVO;
import com.dbs.consent.demo.util.ConsentConfig;
import com.dbs.consent.demo.util.Util;

import org.ksoap2.serialization.SoapObject;

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

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

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

  private Context mContext;
  private ConsentActivity instance;
  private ConsentEvent consentEvent;
  public ArrayList<ConsentFormListVO> arrayList;

  private CustomDeleteAlert customDeleteAlert;

  private String userId  = "";
  public String apiType = "";

  public ConsentHistoryAdapter(AppCompatActivity mActivity, Context mContext, ArrayList<ConsentFormListVO> arrayList, String apiType) {
    this.mActivity = mActivity;
    this.mContext  = mContext;
    this.arrayList = arrayList;
    this.instance  = (ConsentActivity) mContext;
    this.apiType   = apiType;
    this.userId    = Util.getStringPreference(mContext, "userInfo", "userId");
  }

  @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 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.listLayer.setTag(holder);
    holder.tvSubText.setTag(holder);
    return holder;
  }

  @Override
  public void onBindViewHolder(@NonNull ConsentHistoryAdapter.ViewHolder holder, int position) {
    ConsentFormListVO consentFormListVO = arrayList.get(position);
    String pid             = consentFormListVO.getPid();
    String patientName     = consentFormListVO.getPatientName();
    String formName        = consentFormListVO.getFormName();
    String consentState    = consentFormListVO.getConsentState();
    String consentStateEng = consentFormListVO.getConsentStateEng();
    String createUserId    = consentFormListVO.getCreateUserId();

    GradientDrawable tvSubBg = (GradientDrawable) holder.tvSubText.getBackground().getCurrent();
    if (apiType.equals("patient") || apiType.equals("write")) {

      tvSubBg.setColor(ContextCompat.getColor(mContext, R.color.typeRightColor));

      SpannableStringBuilder builder = new SpannableStringBuilder();
      SpannableString colorSpannable = new SpannableString(pid);
      colorSpannable.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.commonColor)), 0, pid.length(), 0);
      builder.append(colorSpannable);
      builder.append(" " + patientName);

      holder.tvTemp.setVisibility(View.GONE);

      GradientDrawable tvSubText = (GradientDrawable) holder.tvSubText.getBackground().getCurrent();
      if (consentStateEng.equals(ConsentConfig.TEMP)) {
        tvSubText.setColor(ContextCompat.getColor(mContext, R.color.tempColor));
      } else if (consentStateEng.equals(ConsentConfig.UNFINISHED)) {
        tvSubText.setColor(ContextCompat.getColor(mContext, R.color.tempColor));
      } else if (consentStateEng.equals(ConsentConfig.ELECTR_CMP)) {
        tvSubText.setColor(ContextCompat.getColor(mContext, R.color.typeRightColor));
      } else if (consentStateEng.equals(ConsentConfig.CERTIFY_CMP)) {
        tvSubText.setColor(ContextCompat.getColor(mContext, R.color.sexNAgeColor));
      } else if (consentStateEng.equals(ConsentConfig.PAPER_OUT)) {
        tvSubText.setColor(ContextCompat.getColor(mContext, R.color.paperOutcolor));
      }

      holder.tvPatientName.setVisibility(View.VISIBLE);
      holder.tvPatientName.setText(builder, TextView.BufferType.SPANNABLE);
      holder.tvSubText.setText(consentState);
    } else if (apiType.equals("centerTemp")) {
      GradientDrawable tvTempBg = (GradientDrawable) holder.tvTemp.getBackground().getCurrent();
      if (consentStateEng.equals(ConsentConfig.TEMP)) {
        tvTempBg.setColor(ContextCompat.getColor(mContext, R.color.tempColor));
        tvSubBg.setColor(ContextCompat.getColor(mContext, R.color.tempColor));
      } else if (consentStateEng.equals(ConsentConfig.UNFINISHED)) {
        tvTempBg.setColor(ContextCompat.getColor(mContext, R.color.tempColor));
        tvSubBg.setColor(ContextCompat.getColor(mContext, R.color.tempColor));
      }else if (consentStateEng.equals(ConsentConfig.ELECTR_CMP)) {
        tvTempBg.setColor(ContextCompat.getColor(mContext, R.color.typeRightColor));
        tvSubBg.setColor(ContextCompat.getColor(mContext, R.color.typeRightColor));
      }

      holder.tvPatientName.setVisibility(View.GONE);
      holder.tvTemp.setText(consentState);

      if (createUserId.equals(userId)) {
        holder.tvTemp.setVisibility(View.VISIBLE);
        holder.tvSubText.setText(mContext.getString(R.string.delete));
        tvSubBg.setColor(ContextCompat.getColor(mContext, R.color.alertColor));
//        holder.tvSubText.setOnClickListener(onClickListener);
      } else {
        holder.tvTemp.setVisibility(View.GONE);
        holder.tvSubText.setText(consentState);
      }

    }

    holder.tvConsentName.setText(formName);

    holder.listLayer.setOnClickListener(onClickListener);
  }

  private View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      ViewHolder holder = (ViewHolder) v.getTag();
      final int position = holder.getLayoutPosition();
      ConsentFormListVO consentFormListVO = arrayList.get(position);
      final String formCd          = consentFormListVO.getFormCode();
      final String formName        = consentFormListVO.getFormName();
      final String consentMstRid   = consentFormListVO.getConsentMstRid();
      final String ocrTag          = consentFormListVO.getOcrTag();
      final String pid             = consentFormListVO.getPid();
      final String inDd            = consentFormListVO.getInDd();
      final String ordType         = consentFormListVO.getOrdType();
      final String ordDeptCd       = consentFormListVO.getOrdDeptCd();
      final String cretNo          = consentFormListVO.getCretNo();
      final String pageCnt         = consentFormListVO.getPrntCnt();

      if (holder.listLayer == v) {
        consentEvent = new ConsentEvent(mContext, instance, consentFormListVO);
        Log.e(TAG, "apiType -- > " + apiType);
        if (apiType.equals("write")) {
          Log.e(TAG, "!!!!!!!!!!!!!!!!!!!!!!!");
          CallBack callBack = new CallBack() {
            @Override
            public void result(final SoapObject result) {
              mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                  PatientInfoVO patientInfoVO = SoapParser.getPatientInfo(result);
                  if (patientInfoVO == null) {
                    instance.showSingButtonDialog(mContext.getString(R.string.failedPatientInfo));
                  } else {
                    consentEvent.consentOpenProc(patientInfoVO, apiType);

                    if (instance.leftMenu.patientListAdapter != null) {
                      instance.leftMenu.patientListAdapter.click = false;
                      instance.leftMenu.patientListAdapter.notifyDataSetChanged();
                    }

                    instance.centerMenu.patientInfoVO = null;
                    instance.centerMenu.clearPatientInfo();

                    ConsentHistoryAdapter adapter = (ConsentHistoryAdapter) instance.history.historyPatientRecyclerView.getAdapter();
                    if (adapter != null) {
                      adapter.arrayList.clear();
                      adapter = null;
//                      adapter.notifyDataSetChanged();

                    }

                  }

                  instance.dismissProgress();
                }
              });
            }

            @Override
            public void stop() {

            }

            @Override
            public void error() {

            }
          };

          instance.showProgress();
          HashMap<String, String> mData = new HashMap<String, String>();
          mData.put("pid", pid);
          mData.put("inDd", inDd);
          mData.put("ordType", ordType);
          mData.put("ordDeptCd", ordDeptCd);
          mData.put("cretNo", cretNo);
          mData.put("instCd", BuildConfig.INST_CD);
//          mData.put("opRsrvNo", opRsrvNo);
          Util.callHttp(mContext, ConsentConfig.HOST_HOSPITAL, ConsentConfig.GET_PATIENT_INFO, mData, callBack);

        } else {
          Log.e(TAG, "#############################");

          consentEvent.consentOpenProc(instance.centerMenu.patientInfoVO, apiType);

          ConsentHistoryAdapter adapter = (ConsentHistoryAdapter) instance.history.historyWriteRecyclerView.getAdapter();
          if (adapter != null) {
            adapter.arrayList.clear();
//            adapter.notifyDataSetChanged();
            adapter = null;
          }
        }

      } else if (holder.tvSubText == v) { // 동의서 삭제
        String message = String.format(mContext.getString(R.string.deleteConsent), formName);
        instance.csAlert.show();
        instance.csAlert.setContent(message, "");
        instance.csAlert.btnConfirm.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            instance.csAlert.dismiss();

            CallBack callBack = new CallBack() {
              @Override
              public void result(final SoapObject result) {
                ((ConsentActivity) mContext).runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                    if (result == null) {
                      stop();
                    } else {
                      String res = result.getProperty("responseData").toString().trim();
                      int intRes = Integer.parseInt(res);

                      if (intRes == -1) {
                        stop();
                      } else {
                        customDeleteAlert.dismiss();
                      }
                    }

                    ((ConsentActivity) mContext).dismissProgress();
                    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", "userId");
            String userDeptCd = Util.getStringPreference(mContext, "userInfo", "deptCd");
            HashMap<String, String> mData = new HashMap<String, String>();
            mData.put("userId", userId);
            mData.put("consentMstRid", consentMstRid);
            mData.put("patientCode", pid);
            mData.put("clnDeptCode", ordDeptCd);
            mData.put("formCd", formCd);
            mData.put("vistType", ordType);
            mData.put("hosType", BuildConfig.INST_CD);
            mData.put("clnDate", inDd);
            mData.put("ocrCode", ocrTag);
            mData.put("cretno", cretNo);
            mData.put("userDeptCd", userDeptCd);
            mData.put("pageCnt", pageCnt);
            mData.put("clientType", ConsentConfig.CLIENT_TYPE);
            mData.put("formName", formName);

            customDeleteAlert = new CustomDeleteAlert(mContext, mData, callBack);
            customDeleteAlert.show();
          }
        });

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

      }

    }
  };

}
