package com.dbs.consent.demo.consent;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

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.sign.SignWrapper;
import com.dbs.consent.demo.util.ConsentConfig;
import com.dbs.consent.demo.util.Util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kr.co.clipsoft.eform.EFormToolkit;
import kr.co.clipsoft.eform.information.RunOption;
import kr.co.clipsoft.eform.type.enumtype.LogLevel;
import kr.co.clipsoft.eform.type.enumtype.Position;
import kr.co.clipsoft.eform.type.enumtype.ScreenOrientation;
import kr.co.clipsoft.eform.type.enumtype.TempSaveCheck;

import static android.content.Context.INPUT_METHOD_SERVICE;

public class ConsentFacade {
  private static final String TAG = "ConsentFacade";
  private Context mContext;
  private ConsentActivity instance;

  private EFormToolkit eFormToolkit;

  public ConsentFacade(Context mContext) {
    this.mContext = mContext;
    this.instance = (ConsentActivity) mContext;
    this.eFormToolkit = new EFormToolkit(mContext);
  }

  private RunOption createRunOption() {
    RunOption runOption = new RunOption();

    runOption.setScreenOrientation(ScreenOrientation.Sensor);  // 가로세로 전환 모드
    runOption.setFirstPageLoad(true);              // 서식 로딩 시 첫 페이지만 로딩
    runOption.setUseCaching(false);                // 로컬 파일 생성하여 캐싱 사용 여부
    runOption.setLogLevel(LogLevel.INFO);            // 로그 레벨
    runOption.setFosLogging(true);                // fos 로그 여부
    runOption.setUseCameraAttachPage(true);                     // 첨지기능 사용여부
//    runOption.setExternalControlDefinedPath(BuildConfig.CONSENT_EFORM_SERVER_URL);
    runOption.setExternalControlDefinedPath("https://ema031.knuh.kr:9090/eformservice.aspx");
    runOption.setParameterDefaultValueClear(false);
    runOption.setInitializeScrollOnPageMove(true);    // 페이지 이동시 스크롤 초기화
    runOption.setAttachPagePosition(Position.Next);    // 첨지 옵션
    runOption.setBottomToolbarButtonsVisibleOnPenDrawMode(true); // 펜드로잉 모드일때 하단 이동 버튼 보이기 여부

    // 저장시 옵션
    runOption.setReturnDataXmlOnSave(true);        // 저장시 dataXml 리턴 여부
    runOption.setDataXmlSaveAsFileOnSave(false);      // 저장시 dataXml 리턴 시 file 여부(true : file, false : String)
    runOption.setImageSaveOption("{'encode':'jpg', 'start-index':0, 'quality':100, 'dpi':150, 'gray':false}"); // 저장될 이미지 타입을 설정함
    runOption.setReturnImageOnSave(true);        // 저장시 이미지 파일 리턴 여부
    runOption.setReturnTempDocumentOnSave(true);    // 저장 시 ept 파일 저장 여부
    runOption.setIncludesDrawingOnDataXml(false);    // 저장시 펜드로잉 정보 저장 여부
    runOption.setReturnPdfOnSave(false);        // 저장 시 PDF 저장 여부

    // 임시 저장시 옵션
    runOption.setReturnDataXmlOnTempSave(true);      // 임시 저장시 dataXml 리턴 여부
    runOption.setDataXmlSaveAsFileOnTempSave(false);    // 임시 저장시 dataXml 리턴 시 file 여부(true : file, false : String)
    runOption.setIncludesDrawingOnTempDocument(true);  // 임시저장시 펜드로잉 정보 저장 여부

    runOption.setUseNextDocumentOpenDialogAfterSave(false);// 연속 출력시 저장 후 알림 여부
    runOption.setSameCheckAsSaveWhenTempSave2(TempSaveCheck.Always);
    runOption.setReturnImageOnTempSave2(true);

//    runOption.setUiStyle("{"
//        + "'required-input':{'border':{'visible':'false','color':{'b':0,'g':0,'r':225,'a':120},'width':2},'background':{'visible':'true','color':{'b':0,'g':0,'r':225,'a':120}}}"
//        + ",'toast-message':{'signature-missing-data':{'text':'" + mContext.getString(R.string.emptySign) + "'}}"
//        + ",'toolbar':{"
//        + "        'buttons':{"
//        + "              'tempsave2':{'visible':'true','enabled':'true','text':'" + mContext.getString(R.string.confirmSave) + "'}"
//        + "              ,'record':{'visible':'false'}"
//        + "              ,'information':{'visible':'true'}"
//        + "              ,'tempsave':{'visible':'true','enabled':'true','text':'" + mContext.getString(R.string.tempList) + "'}"
//        + "              ,'save':{'visible':'true','enabled':'true','text':'" + mContext.getString(R.string.certifySave) + "'}"
//        + "              ,'exit':{'visible':'true','text':'" + mContext.getString(R.string.exit) + "'}"
//        + "              ,'pageattach':{'visible':'true'}"
//        + "              ,'page-number':{'current':{'text-color':{'b':116,'g':186,'r':14,'a':255}}"
//        + "        }"
//        + "}"
//        + ",'move-next':{"
//        + "     'buttons':{"
//        + "       'save-move':{'text':'저장 후 이동','visible':true,'enabled':true}"
//        + "        ,'tempsave-move':{'text':'임시저장 후 이동','visible':true,'enabled':true}"
//        + "      ,'tempsave2-move':{ 'text':'임시저장2 후 이동','visible':false ,'enabled':true}"
//        + "        ,'move':{'text':'저장 없이 이동','visible':true ,'enabled':true}"
//        + "   }"
//        + "}}}"
//    ); // 툴바 및 UI 관련 옵션 설정

    runOption.setUiStyle(getUiStyle());

    return runOption;
  }

  public void startConsent(HashMap consentData, String certPass, String apiType) {
//    HashMap<String, String> globalParam = (HashMap<String, String>) consentData.get("globalParam");
//    ArrayList<HashMap<String, String>> formList = (ArrayList<HashMap<String, String>>) consentData.get("formListParam");

    String userId = Util.getStringPreference(mContext, "userInfo", "userId");
    String fos = createFOS(consentData);

//    Log.e(TAG, "create fos -- > " + fos);
//    Util.LOG(ConsentFacade.class, "create fos -- > " + fos);

    eFormToolkit.setExitEventHandler(new EformExitEventHandler());
    eFormToolkit.setResultEventHandler(new EFormSaveHandler(mContext, eFormToolkit, consentData, apiType));

    eFormToolkit.setRunOption(createRunOption());
    if (SignWrapper.getInstance().isCertificate(userId) == true || certPass.equals("Y")) {
      String result = eFormToolkit.startEFormViewer(fos);

      if (result.equals("ERROR_004")) {
        return;
      }

      if (!result.equals("SUCCESS")) {
        String message = "";
        if (result.equals("ERROR_000")) {
          message = mContext.getString(R.string.ERROR_000);
        } else if (result.equals("ERROR_001")) {
          message = mContext.getString(R.string.ERROR_001);
        } else if (result.equals("ERROR_002")) {
          message = mContext.getString(R.string.ERROR_002);
        } else if (result.equals("ERROR_006")) {
          message = String.format(mContext.getString(R.string.permissionDenied), mContext.getString(R.string.viewer));
        }
        instance.csAlert.show();
        instance.csAlert.setContent(message, ConsentConfig.ALERT_BTN_TYPE);
        String finalResult = result;
        instance.csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            instance.csAlert.dismiss();
          }
        });
      }

    } else {
      //공인인증 정보가 없을때
      startCertificate(mContext, eFormToolkit, fos, userId);
    }

  }

  private void startCertificate(final Context context, final EFormToolkit eFormToolkit, final String fos, final String userId) {
    final EditText passwordEdit = new EditText(context);
    passwordEdit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    passwordEdit.setTransformationMethod(PasswordTransformationMethod.getInstance());
    Util.setCursorColor(passwordEdit, R.color.black);

    final InputMethodManager imm = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);

    DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        String password = passwordEdit.getText().toString();

        try {
          // 인증서 인증
          if (SignWrapper.getInstance().certificate(context, userId, password)) {
            eFormToolkit.startEFormViewer(fos);
          } else {
            Util.getOKDialog(context, context.getString(R.string.emptyCertPw), context.getString(R.string.certAuthFail), null).show();
          }

          imm.hideSoftInputFromWindow(passwordEdit.getWindowToken(), 0);
        } catch (Exception e) {
          e.printStackTrace();
          Util.getOKDialog(context, context.getString(R.string.emptyCertPw), e.getMessage(), null).show();
        }
      }
    };

    DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        imm.hideSoftInputFromWindow(passwordEdit.getWindowToken(), 0);
      }
    };

    AlertDialog dialog = Util.getPasswordInputDialog(context, context.getString(R.string.emptyCertPw), context.getString(R.string.certAuthFail), okListener, cancelListener);
    dialog.setView(passwordEdit);
    dialog.show();
  }

  public String createFOS(HashMap consentData) {
    String fos = "";
    fos = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
    fos += "<fos version='1.0'>";
    fos += "  <global>";
    fos += this.createFosPageTemplate();
    fos += "    <parameters>"; // form-list의 모든 서식에 적용될 파라미터
    fos += "            <param key='UrlParam'>" + BuildConfig.CONSENT_SERVER_URL + "</param>";
//    fos += "            <param key='UrlParam'>" + "https://ema031.knuh.kr:9091" + "</param>";
    fos += this.createParamString((HashMap<String, String>) consentData.get("globalParam"));
    fos += "    </parameters>";
    fos += "   </global>";
    fos += "  <form-list>";
    fos += this.createFormString((List<Map<String, String>>) consentData.get("formListParam"));
    fos += "  </form-list>";
    fos += "</fos>";
    return fos;
  }

  private String createFosPageTemplate() {
    String pageTemplate = "";
    pageTemplate += "<page-template path='" + BuildConfig.CONSENT_EFORM_SERVER_URL + "' request-encode ='utf-8' response-encode ='utf-8'>";
    pageTemplate += "  <template-get-parameters>";
    pageTemplate += "    <post-param key='OP'>";
    pageTemplate += "      <![CDATA[PAGE_TEMPLATE]]>";
    pageTemplate += "    </post-param>";
    pageTemplate += "    <post-param key='PD'>";
    pageTemplate += "      <![CDATA[";
    pageTemplate += "        <data>";
    pageTemplate += "          <action>GET_LIST</action>";
    pageTemplate += "          <params>";
    pageTemplate += "            <param name='adaptername'>defaultadapter</param>";
    pageTemplate += "          </params>";
    pageTemplate += "        </data>";
    pageTemplate += "      ]]>";
    pageTemplate += "     </post-param>";
    pageTemplate += "  </template-get-parameters>";
    pageTemplate += "</page-template>";
    return pageTemplate;
  }

  private String createFormString(List<Map<String, String>> formMapList) {
    String fos = "";
    for (int i = 0; i < formMapList.size(); i++) {
      Map<String, String> formMap = formMapList.get(i);
      String rid = formMap.get("rid");
      String guid = formMap.get("guid");
      boolean newForm = true;
      String newConsent = formMap.get("newConsent");

      if (newConsent != null && "true".equals(newConsent)) {
        newForm = true;
      } else {
        newForm = false;
      }

      fos += "    <form name='noname' open-sequence='" + (i + 1) + "' path='" + BuildConfig.CONSENT_EFORM_SERVER_URL + "' request-encode='utf-8' response-encode='utf-8'>";
      fos += "      <parameters>";
      fos += this.createParamString((HashMap<String, String>) formMap);
      fos += "      </parameters>";
      fos += "      <form-get-parameters>";
      fos += "        <post-param key='OP'><![CDATA[" + (newForm == true ? "VIEWER_FORM" : "VIEWER_DATA") + "]]></post-param>";
      fos += "        <post-param key='PD'>";
      fos += "        <![CDATA[";
      fos += "          <data>";
      fos += "          <action>" + (newForm == true ? "GET" : "GET_DATA") + "</action>";
      fos += "            <params>";
      fos += "              <param name='adaptername'>defaultadapter</param>";

      if (newForm) {
        fos += "                <param name='type'>guid</param>";
        fos += "                <param name='guid'>" + guid + "</param>";
        fos += "                <param name='version'>-1</param>";
      } else {
        fos += "                <param name='rid'>" + rid + "</param>";
      }

      fos += "            </params>";
      fos += "          </data>";
      fos += "        ]]>";
      fos += "        </post-param>";
      fos += "      </form-get-parameters>";
      fos += "    </form>";
    }
    return fos;
  }

  /**
   * @param param
   * @return
   */
  private String createParamString(HashMap<String, String> param) {
    StringBuffer paramStr = new StringBuffer();
    if (param != null && !param.isEmpty()) {
      for (String key : param.keySet()) {
        if (key.equals("newConsent")) {
        }
        paramStr.append("<param key=\'").append(key).append("\'>");
        paramStr.append("<![CDATA[");
        paramStr.append(Util.getNull2EmptyString(param.get(key)));
        paramStr.append("]]>");
        paramStr.append("</param>");
      }
    }
    return paramStr.toString();
  }

  private String getUiStyle() {

    String visible = "false";
    if (!instance.indexPage.equals("O")) {
      if (instance.indexPage.equals("SR")) {
        if (instance.leftMenu.patientState.equals("0")) {
          visible = "true";
        } else {
          if (ConsentConfig.SETTING_DATA.get("ELECTR_CMP").equals("Y")) {
            visible = "true";
          }
        }
      } else {
        if (ConsentConfig.SETTING_DATA.get("ELECTR_CMP").equals("Y")) {
          visible = "true";
        }
      }

    } else if (instance.indexPage.equals("O")) {
      visible = "true";
    }

    if(instance.jobKindCd.indexOf("03") != 0){
      visible = "false";
    }

    String uiStyle = "{                                                                                                                             " +
                     "  'required-input': {                                                                                                         " +
                     "    'border': {                                                                                                               " +
                     "      'visible': 'false',                                                                                                     " +
                     "      'color': {                                                                                                              " +
                     "        'b': 0,                                                                                                               " +
                     "        'g': 0,                                                                                                               " +
                     "        'r': 225,                                                                                                             " +
                     "        'a': 120                                                                                                              " +
                     "      },                                                                                                                      " +
                     "      'width': 2                                                                                                              " +
                     "    },                                                                                                                        " +
                     "    'background': {                                                                                                           " +
                     "      'visible': 'true',                                                                                                      " +
                     "      'color': {                                                                                                              " +
                     "        'b': 0,                                                                                                               " +
                     "        'g': 0,                                                                                                               " +
                     "        'r': 225,                                                                                                             " +
                     "        'a': 120                                                                                                              " +
                     "      }                                                                                                                       " +
                     "    }                                                                                                                         " +
                     "  },                                                                                                                          " +
                     "  'toast-message': {                                                                                                          " +
                     "    'signature-missing-data': {                                                                                               " +
                     "      'text': '" + mContext.getString(R.string.emptySign) + "'                                                                " +
                     "    }                                                                                                                         " +
                     "  },                                                                                                                          " +
                     "  'toolbar': {                                                                                                                " +
                     "    'buttons': {                                                                                                              " +
                     "      'record': {                                                                                                             " +
                     "        'visible': 'false'                                                                                                    " +
                     "      },                                                                                                                      " +
                     "      'information': {                                                                                                        " +
                     "        'visible': 'true'                                                                                                     " +
                     "      },                                                                                                                      " +
                     "      'tempsave2': {                                                                                                          " +
                     "        'visible': '" + visible + "',                                                                                                    " +
                     "        'enabled': 'true',                                                                                                    " +
                     "        'text': '" + mContext.getString(R.string.confirmSave) + "'                                                            " +
                     "      },                                                                                                                      " +
                     "      'tempsave': {                                                                                                           " +
                     "        'visible': 'true',                                                                                                    " +
                     "        'enabled': 'true',                                                                                                    " +
                     "        'text': '" + mContext.getString(R.string.tempList) + "'                                                               " +
                     "      },                                                                                                                      " +
                     "      'save': {                                                                                                               " +
                     "        'visible': 'true',                                                                                                    " +
                     "        'enabled': 'true',                                                                                                    " +
                     "        'text': '" + mContext.getString(R.string.certifySave) + "'                                                            " +
                     "      },                                                                                                                      " +
                     "      'exit': {                                                                                                               " +
                     "        'visible': 'true',                                                                                                    " +
                     "        'text': '" + mContext.getString(R.string.exit) + "'                                                                   " +
                     "      },                                                                                                                      " +
                     "      'pageattach': {                                                                                                         " +
                     "        'visible': 'true'                                                                                                     " +
                     "      },                                                                                                                      " +
                     "      'page-number': {                                                                                                        " +
                     "        'current': {                                                                                                          " +
                     "          'text-color': {                                                                                                     " +
                     "            'b': 116,                                                                                                         " +
                     "            'g': 186,                                                                                                         " +
                     "            'r': 14,                                                                                                          " +
                     "            'a': 255                                                                                                          " +
                     "          }                                                                                                                   " +
                     "        }                                                                                                                     " +
                     "      }                                                                                                                       " +
                     "    },                                                                                                                        " +
                     "    'move-next': {                                                                                                            " +
                     "      'buttons': {                                                                                                            " +
                     "        'save-move': {                                                                                                        " +
                     "          'text': '" + String.format(mContext.getString(R.string.saveNext), mContext.getString(R.string.certifySave)) + "',   " +
                     "          'visible': true,                                                                                                    " +
                     "          'enabled': true                                                                                                     " +
                     "        },                                                                                                                    " +
                     "        'tempsave-move': {                                                                                                    " +
                     "          'text': '" + String.format(mContext.getString(R.string.saveNext), mContext.getString(R.string.tempList)) + "',      " +
                     "          'visible': true,                                                                                                    " +
                     "          'enabled': true                                                                                                     " +
                     "        },                                                                                                                    " +
                     "        'tempsave2-move': {                                                                                                   " +
                     "          'text': '" + String.format(mContext.getString(R.string.saveNext), mContext.getString(R.string.confirmSave)) + "',   " +
                     "          'visible': true,                                                                                                    " +
                     "          'enabled': true                                                                                                     " +
                     "        },                                                                                                                    " +
                     "        'move': {                                                                                                             " +
                     "          'text': '"+ mContext.getString(R.string.notSaveNext) +"',                                                           " +
                     "          'visible': true,                                                                                                    " +
                     "          'enabled': true                                                                                                     " +
                     "        }                                                                                                                     " +
                     "      }                                                                                                                       " +
                     "    }                                                                                                                         " +
                     "  },                                                                                                                          " +
                     "  'dialog': {                                                                                                                 " +
                     "    'save': {                                                                                                                 " +
                     "      'title': '" + mContext.getString(R.string.certifySave) + "',                                                            " +
                     "      'contents': '" + String.format(mContext.getString(R.string.saveAction), mContext.getString(R.string.certifySave)) + "'  " +
                     "    },                                                                                                                        " +
                     "    'temp-save': {                                                                                                            " +
                     "      'title': '" + mContext.getString(R.string.tempList) + "',                                                               " +
                     "      'contents': '" + String.format(mContext.getString(R.string.saveAction), mContext.getString(R.string.tempList)) + "'     " +
                     "    },                                                                                                                        " +
                     "    'temp-save2': {                                                                                                           " +
                     "      'title': '" + mContext.getString(R.string.confirmSave) + "',                                                            " +
                     "      'contents': '" + String.format(mContext.getString(R.string.saveAction), mContext.getString(R.string.confirmSave)) + "'  " +
                     "    }                                             " +
                     "  }                                               " +
                     "}                                                 ";
    return uiStyle;
  }
}
