package com.dbs.mplus.knuh.consent.sign;

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

import com.androidKmi.KmiApi;
import com.dbs.mplus.knuh.util.ConsentConfig;
import com.lumensoft.ks.KSCertificate;
import com.lumensoft.ks.KSCertificateLoader;
import com.lumensoft.ks.KSCertificateManager;
import com.lumensoft.ks.KSException;
import com.lumensoft.ks.KSSign;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

public class SignWrapper {
  
  private static final String TAG = "SignWrapper";
  private static SignWrapper instance;
  private KmiApi kmiApi;
  
  private Map<String, CertificateInfo> certificateMap;
  
  public SignWrapper() {
    kmiApi = new KmiApi();
    certificateMap = new HashMap<String, CertificateInfo>();
  }
  
  public static SignWrapper getInstance() {
    if(instance == null) {
      instance = new SignWrapper();
    }
    return instance;
  }
  
  public void deleteAll() {
    for (String key : certificateMap.keySet()) {
      if (certificateMap.get(key) != null) {
        boolean result = this.kmiApi.LocalDelKeyAndCert(certificateMap.get(key).getCertificate().getSubjectDn());
      }
    }
    
    this.certificateMap.clear();
  }
  
  /**
  * 인증여부 확인
  * @author jksong
  * @Param
  * @since 2019-08-09 오후 2:05
  **/
  public boolean isCertificate(String userId) {
    return this.certificateMap.containsKey(userId);
  }
  
  /**
   * 서명
   * @param userId
   * @param signData
   * @return
   */
  public String signData(String userId, String signData) {
    String certResult = null;
    CertificateInfo certificate = this.certificateMap.get(userId);
    if(certificate != null) {
      try {
        byte[] result = null;
        // 서명데이터 구분자 ^ 빼고
        String hashValue = signData.replaceAll("\\^", "");
        result = KSSign.koscomSign(certificate.getCertificate(), hashValue, certificate.getPassword());
        certResult = new String(Base64.encode(result, Base64.DEFAULT));
      } catch (KSException e) {
        e.printStackTrace();
      }
    }
    return certResult;
  }
  
  /**
  * 인증서 인증
  * @author jksong
  * @Param Context
  * @Param userId : 사용자 아이디
  * @Param password : 인증서 비밀번호
  * @since 2019-08-09 오후 2:06
  **/
  public boolean certificate(Context context, String userId, String password) {
    String certDN = downloadCertificate(userId);
    Log.e(TAG, "certDN -- > " + certDN);
    if (certDN == null) {
      return false;
    }
  
    Vector<KSCertificate> certificateVector = null;
    int index = 0;
    boolean certFlag = false;
    
    try {
      certificateVector = KSCertificateLoader.getUserCertificateList(context);
      index = KSCertificateLoader.getUserCertificate(certDN, context);
      if (index < 0) {
        return false;
      }
      
      KSCertificate certificate = certificateVector.get(index);
      certFlag = KSCertificateManager.checkPwd(certificate, password);
      
      if (certFlag == false) {
        return false;
      }
      
      CertificateInfo certificateInfo = new CertificateInfo(certificate, password);
      certificateMap.put(userId, certificateInfo);
    } catch (KSException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    
    return true;
  }
  
  /**
  * 인증서 DN 정보 가져오기
  * @author jksong
  * @Param 
  * @since 2019-08-09 오후 2:07
  **/
  private String downloadCertificate(String userId) {
    String certDN = null;
    
    if (kmiApi.kmsConnect(ConsentConfig.CERTIFICATE_IP, ConsentConfig.CERTIFICATE_PORT) == true) {
      certDN = kmiApi.GetKeyAndCert(userId);
    }
  
    kmiApi.kmsDisconnect();
    return certDN;
  }
  

}
