package com.dbs.dbsec.consent;

import android.content.Context;
import android.util.Base64;
import android.util.Log;
import android.util.TypedValue;

import com.dbs.dbsec.BuildConfig;
import com.dbs.dbsec.activity.ConsentActivity;
import com.dbs.dbsec.httpTask.CallBack;
import com.dbs.dbsec.util.Common;
import com.dbs.dbsec.util.ConsentConfig;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;

import kr.co.clipsoft.eform.EFormToolkit;
import kr.co.clipsoft.eform.event.IEventHandler;
import kr.co.clipsoft.eform.event.ResultEventArgs;

import static kr.co.clipsoft.eform.type.enumtype.ResultCode.TEMP_SAVE;

public class EformSaveEventHandler implements IEventHandler<ResultEventArgs> {

  private static final String TAG = EformSaveEventHandler.class.getSimpleName();
  private Context mContext;
  private EFormToolkit eFormToolkit;
  private HashMap consentData;
  private ConsentActivity instance;

  private HashMap saveData;

  private String btnType = "";
  private String certify = "";

  public EformSaveEventHandler(Context mContext, EFormToolkit eFormToolkit, HashMap consentData, String certify) {
    this.mContext = mContext;
    this.eFormToolkit = eFormToolkit;
    this.instance = (ConsentActivity) mContext;
    this.consentData = consentData;
    this.saveData = new HashMap();
    this.certify = certify;
  }

  @Override
  public void eventReceived(Object o, ResultEventArgs resultEventArgs) {
    saveData = createSaveData(resultEventArgs, consentData);

    switch (resultEventArgs.getResultCode()) {
      case TEMP_SAVE:
        Common.callHttp(mContext, ConsentConfig.SAVE_TEMP_DATA, saveData, callBack);

        break;
    }
  }

  private HashMap createSaveData(ResultEventArgs resultEventArgs, HashMap consentData) {
    HashMap<String, String> globalParam = (HashMap<String, String>) consentData.get("globalParam");
    ArrayList<HashMap<String, String>> formList = (ArrayList<HashMap<String, String>>) consentData.get("consentArray");

    String consentMstRidStr = formList.get(0).get("consentMstRid");
    String cretNoStr        = globalParam.get("par_patientCretno") == null ? formList.get(0).get("par_patientCretno") : globalParam.get("par_patientCretno");

    consentMstRidStr = consentMstRidStr.equals("") ? "0" : consentMstRidStr;
    cretNoStr = cretNoStr.equals("") ? "0" : cretNoStr;

    String userId = Common.getStringPreference(mContext, "userInfo", "userId");
    String userDeptCd = Common.getStringPreference(mContext, "userInfo", "deptCd");
    String pid = globalParam.get("par_patientId") == null ? formList.get(0).get("par_patientId") : globalParam.get("par_patientId");
    String formId               = formList.get(0).get("formId");
    String formCode             = formList.get(0).get("formCode");
    String patientDeptCd        = globalParam.get("patientDeptCd") == null ? formList.get(0).get("patientDeptCd") : globalParam.get("patientDeptCd");
    String dataXml              = resultEventArgs.getDataXml();
    int consentMstRid           = Integer.parseInt(consentMstRidStr);
    Log.e(TAG, "consentMstRid -- > " + consentMstRid);
    int reWriteConsentMstRid    = certify.equals("CERTIFY_CMP") ? consentMstRid : 0;
    String deviceType           = "AND";
    String deviceMacAddr        = Common.getMACAddress();
    String ordType              = globalParam.get("ordType") == null ? formList.get(0).get("ordType") : globalParam.get("ordType");
    String instCd               = BuildConfig.INST_CD;
    String inDd                 = globalParam.get("par_patientClnDt") == null ? formList.get(0).get("par_patientClnDt") : globalParam.get("par_patientClnDt");
    String dSchDd               = globalParam.get("dSchDd");
    String ward                 = globalParam.get("par_patientWardNo");
    String roomCd               = globalParam.get("par_patientRoomNo");
    String ocrTag               = formList.get(0).get("par_ocrCd");
    int cretNo                  = globalParam.get("par_patientCretno") == null ? Integer.parseInt(formList.get(0).get("par_patientCretno")) : Integer.parseInt(globalParam.get("par_patientCretno"));
    String mainDrId             = globalParam.get("mainDrId") == null ? formList.get(0).get("mainDrId") : globalParam.get("mainDrId");
    String formPageCnt          = String.valueOf(resultEventArgs.getTotalPagesCount());
    String actionKind           = "P"; // 임시저장 : P, 인증저장 : C
    String opRrsvNo             = globalParam.get("par_opRsrvNo");
    String consentState         = "TEMP"; // 임시저장 : TEMP, 인증저장 : CERTIFY_CMP, 확인저장 : ELECTR_CMP
    int orderNo                 = 0;
    String orderName            = "";
    String orderCd              = "";

    String eptFilePath = resultEventArgs.getTempFilePath();
    StringBuffer formXml = new StringBuffer();
    if (eptFilePath != null && "".equals(eptFilePath) == false) {
      try {
        BufferedReader br = new BufferedReader(new FileReader(eptFilePath));
        while (br.ready()) {
          formXml.append(br.readLine());
        }
      } catch(Exception e) {
        e.printStackTrace();
        this.eFormToolkit.sendEFormViewerCancelEvent("EPT 파일을 읽을 수 없습니다.");
      }
    }

    HashMap mData = new HashMap();

    try {
      String compress = Common.base64Encode(Common.zipStringToBytes(formXml.toString()));
      mData.put("formXml", compress);
      compress = Common.base64Encode(Common.zipStringToBytes(dataXml));
      mData.put("dataXml", compress);
    } catch(Exception e) {
      e.printStackTrace();
    }
    mData.put("userId", userId);
    mData.put("userDeptCd", userDeptCd);
    mData.put("pid", pid);
    mData.put("formId", formId);
    mData.put("formCd", formCode);
    mData.put("patientDeptCd", patientDeptCd);

    mData.put("consentMstRid", consentMstRid);
    mData.put("reWriteConsentMstRid", reWriteConsentMstRid);
    mData.put("deviceType", deviceType);
    mData.put("deviceMacAddr", deviceMacAddr);
    mData.put("ordType", ordType);
    mData.put("instCd", instCd);
    mData.put("inDd", inDd);
    mData.put("ward", ward);
    mData.put("roomCd", roomCd);
    mData.put("ocrTag", ocrTag);
    if (cretNo != 0) {
      mData.put("cretNo", cretNo);
    }
    mData.put("mainDrId", mainDrId);
    mData.put("formPageCnt", formPageCnt);
    mData.put("opRrsvNo", opRrsvNo);
    mData.put("orderNo", orderNo);
    mData.put("orderName", orderName);
    mData.put("orderCd", orderCd);
    mData.put("dSchDd", dSchDd);
    mData.put("deviceMacAddr", Common.getMACAddress());
    mData.put("actionKind", "P");
    mData.put("consentState", "TEMP");
    Log.e(TAG, "mData -- > " + mData);

    return mData;
  }

  private CallBack callBack = new CallBack() {
    @Override
    public void result(String result) {
      Log.e(TAG, "saveEvent -- > " + result);
      ((ConsentActivity) mContext).runOnUiThread(new Runnable() {
        @Override
        public void run() {
          eFormToolkit.sendEFormViewerOkEvent();
        }
      });
    }

    @Override
    public void stop() {

    }

    @Override
    public void error() {

    }
  };
}
