
package com.reactlibrary;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.util.Map;
import java.util.*;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.ByteArrayOutputStream;
import android.util.Base64;

import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.BaseActivityEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Callback;

import org.json.JSONException;
import org.json.JSONObject;

import com.vnptit.idg.sdk.utils.KeyIntentConstants;
import com.vnptit.idg.sdk.utils.SDKEnum;

import com.vnptit.idg.sdk.service.SDKServiceUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.vnptit.idg.sdk.model.AddFaceObject;
import com.vnptit.idg.sdk.model.AddFaceRequest;
import com.vnptit.idg.sdk.model.BaseResultResponse;
import com.vnptit.idg.sdk.model.CustomerInformation;
import com.vnptit.idg.sdk.model.DriverLicense;
import com.vnptit.idg.sdk.model.ExtraInfoObject;
import com.vnptit.idg.sdk.model.IdentityCard;
import com.vnptit.idg.sdk.model.ObjectSearchFace;
import com.vnptit.idg.sdk.model.Passport;

public class RNEkycVnptSdkModule extends ReactContextBaseJavaModule {

  private Callback mResultCallback, mErrorCallback;
  private static final int REQUEST_EKYC = 1001;
  private static final String CANCELLED = "cancelled";
  private static final String TEXT = "text";
  private static final String FORMAT = "format";
  private static final String LOG_TAG = "ekyc_vnpt";
 
  private  String ACCESS_TOKEN = "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicmVzdHNlcnZpY2UiXSwidXNlcl9uYW1lIjoidGVzdHBvY0BtYi5jb20iLCJhdXRob3JpdGllcyI6WyJVU0VSIl0sImp0aSI6ImVjYzNkMzJmLWFmYjgtNDI4Yy05MmM3LWI5ZGZmNWFhZGRlMiIsImNsaWVudF9pZCI6ImFkbWluYXBwIiwic2NvcGUiOlsicmVhZCJdfQ.H6fBhTrfftFxAdkuDUt-QWkI2qRr7sanTHTjibr1GVBiFfmVrRWG9j571eUowaPBuevniganjhTrOkb36AwK5yHClekoeJyJvZuk2U8w30JWL31w1ktRxDFMrTSxcVdTyDew4t5OrmL5NXAKKwI1-9eEcy3USdh54oRJTZpTP1W7tXKAZAd0vEmeenGJN6ztiNV1MxfvHznqsYZQRlRXLYZVaUF4fqNoYqc6wsjiwKupomX_8wdM9RZG_qxOfpPOcL2nNTmMWq6e1cjJ0vPFFHKMvS6_o2kq8lqUFoo_5oqj84wmH-ML4c5KUKGjzENM0ykknbFNHIxmJaBhSRVzYA";
  private  String TOKEN_ID = "9351809c-8e2b-451b-ba59-0971ce4ec983";
  private  String TOKEN_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIDiUTSKaloWUDXJkd/bojdOeMnYDCk4oIc7B8i+ENYhbAroZuF+rSkEwMZIhBAtHysP0OeA7PAlx35ewps7TR8CAwEAAQ==";

  private String UNIT = "MBBANK";
  // private String UNIT = "test1";
  //private int type = 0;//set default

  public RNEkycVnptSdkModule(ReactApplicationContext reactContext) {
    super(reactContext);
    reactContext.addActivityEventListener(mActivityEventListener);
  }

  @Override
  public String getName() {
    return "RNEkycVnptSdk";
  }

  private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() {

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
      if (requestCode == REQUEST_EKYC) {
        if (mResultCallback != null) {
          if (resultCode == Activity.RESULT_OK) {
            Map<String, String> mapData = new HashMap<String, String>();
            JSONObject obj = new JSONObject();            
            
            StringBuilder result = new StringBuilder();
            try {
              String strDataInfo = data.getStringExtra("INFO_RESULT");
              String strDataCompare = data.getStringExtra("COMPARE_RESULT");
              String strDataLiveness = data.getStringExtra("LIVENESS_RESULT");
              String strNetworkProblem = data.getStringExtra("NETWORK_PROBLEM");
              String strDataCheckMaskedFace = data.getStringExtra("MASKED_FACE_RESULT");

              String strLivenessCardFront = data.getStringExtra("LIVENESS_CARD_FRONT_RESULT"); 
     	      String strLivenessCardBack = data.getStringExtra("LIVENESS_CARD_REAR_RESULT");
              
              String strDataImageFront = getImgBase64FromPath(data.getStringExtra("FRONT_IMAGE"));
              String strDataImageBack = getImgBase64FromPath(data.getStringExtra("REAR_IMAGE"));
              String strDataImageFace = getImgBase64FromPath(data.getStringExtra("PORTRAIT_IMAGE"));
              
              String strDataHashPortrait = data.getStringExtra("HASH_PORTRAIT");

              if (strDataCompare == null || strDataCompare == "") {
                strDataCompare = "";
              }
              if (strDataLiveness == null || strDataLiveness == "") {
                strDataLiveness = "";
              }
			        if (strDataCheckMaskedFace == null || strDataCheckMaskedFace == "") {
                strDataCheckMaskedFace = "";
              }
              if (strLivenessCardFront == null || strLivenessCardFront == ""){
                strLivenessCardFront = "";
              }
              if (strLivenessCardBack == null || strLivenessCardBack == ""){
                strLivenessCardBack = "";
              }

              if (strNetworkProblem == null || strNetworkProblem == "null") {
                strNetworkProblem = "success";                		
                mapData.put("info", strDataInfo);	
                mapData.put("compare", strDataCompare);	
                mapData.put("maskedface", strDataCheckMaskedFace);	
                mapData.put("liveness", strDataLiveness);	
                mapData.put("imageFront", strDataImageFront);
                mapData.put("imageBack", strDataImageBack);
                mapData.put("imageFace", strDataImageFace);
                mapData.put("network", strNetworkProblem);	                
                mapData.put("livenessCardFront", strLivenessCardFront);
                mapData.put("livenessCardBack", strLivenessCardBack);
                mapData.put("hashPortrait", strDataHashPortrait);
              } else {
                strNetworkProblem = "timeout";                
                mapData.put("network", strNetworkProblem);
              }          
              
              obj = new JSONObject(mapData);      

              // JSONObject infoObj = new JSONObject(strDataInfo);    
              // String dataHash = infoObj.getString("dataSign");
              // Log.d(LOG_TAG, "dataHash " + dataHash);
              // String rsSearchFace = SDKServiceUtils.searchFace("https://explorer.idg.vnpt.vn/face-service/v2/face/search", dataHash, "MBBANK");
              // Log.d(LOG_TAG, "SDKServiceUtils " + rsSearchFace);


            } catch (Exception e) {
              Log.d(LOG_TAG, "This should never happen");
            }
             mResultCallback.invoke(obj.toString());

          } else if (resultCode == Activity.RESULT_CANCELED) {
            //Toast.makeText(getReactApplicationContext(), "Cancelled", Toast.LENGTH_LONG).show();
            Log.d(LOG_TAG, "Cancelled");
            if(mErrorCallback != null)
              mErrorCallback.invoke("Cancelled");
          } else {
            //Toast.makeText(getReactApplicationContext(), "Unexpected error", Toast.LENGTH_LONG).show();
            Log.d(LOG_TAG, "Unexpected error");
            if(mErrorCallback != null)
              mErrorCallback.invoke("Unexpected error");
          }
        }
      }
    }

  };

  @ReactMethod
  private void initVnptEkyc(int type, Callback resultCallback, Callback errorCallback){
    mResultCallback = resultCallback;
    mErrorCallback = errorCallback;
    Activity currentActivity = getCurrentActivity();

    if (currentActivity == null) {
      errorCallback.invoke("Activity doesn't exist");
      return;
    }

    Intent intent = null;
    try {
      //JSONObject jsonObject = new JSONObject(data);
      //ACCESS_TOKEN = jsonObject.getString("accessToken");
      //TOKEN_ID = jsonObject.getString("tokenId");
      //TOKEN_KEY = jsonObject.getString("tokenKey");
      //type = jsonObject.getInt("type");

      //intent = new Intent(currentActivity,
              //Class.forName("com.vnptit.idg.sdk.activity.VnptIdentityAdvanceActivity"));//danh cho ban nang cao
      
      intent = new Intent(currentActivity,
              Class.forName("com.vnptit.idg.sdk.activity.VnptIdentityActivity"));//danh cho ban co ban

    } catch (Exception e) {
      e.printStackTrace();
    }

    if (intent != null) {

      if(type != 0){
        intent.putExtra("DOCUMENT_TYPE", type);
      } 

      intent.putExtra(KeyIntentConstants.ACCESS_TOKEN, ACCESS_TOKEN);
      intent.putExtra(KeyIntentConstants.TOKEN_ID, TOKEN_ID);
      intent.putExtra(KeyIntentConstants.TOKEN_KEY, TOKEN_KEY);
      intent.putExtra(KeyIntentConstants.VERSION_SDK, SDKEnum.VersionSDKEnum.ADVANCED.getValue());
      intent.putExtra(KeyIntentConstants.SHOW_RESULT, false);//false-return to module, true-show result in sdk
      intent.putExtra(KeyIntentConstants.CAMERA_FOR_PORTRAIT, 0);
      intent.putExtra(KeyIntentConstants.CALL_ADD_FACE, false);
      
      if(type != 0){
        intent.putExtra(KeyIntentConstants.SELECT_DOCUMENT, false);  
      }else{
        intent.putExtra(KeyIntentConstants.SELECT_DOCUMENT, true);
        intent.putExtra(KeyIntentConstants.TITLE_SELECT,"Xác minh thông tin");
        intent.putExtra(KeyIntentConstants.SUBTITLE_SELECT,"<span style=\"font-family: '-apple-system', 'HelveticaNeue'; font-size: 14\">Qúy khách vui lòng lựa chọn loại giấy tờ tùy thân <u> đã sử dụng để đăng ký dịch vụ eMB tại MBBank</u> để xác minh thông tin</span>");		
      }	
      
      intent.putExtra(KeyIntentConstants.CHECK_MASKED_FACE, true);
      intent.putExtra(KeyIntentConstants.LIVENESS_ADVANCED, true);
      intent.putExtra(KeyIntentConstants.ADD_FACE_TITLE, "MB");
      intent.putExtra(KeyIntentConstants.LANGUAGE, SDKEnum.LanguageEnum.VIETNAMESE.getValue());
      intent.putExtra(KeyIntentConstants.HIDE_TRADE_MARK, true);
      
      //add new
      intent.putExtra(KeyIntentConstants.SHOW_SWITCH, true);
      intent.putExtra(KeyIntentConstants.VALIDATE_POSTCODE, true);
      intent.putExtra(KeyIntentConstants.CHECK_LIVENESS_CARD, true); 

      currentActivity.startActivityForResult(intent, REQUEST_EKYC);
    }

  }
  
  private String getImgBase64FromPath(String _path){

    if(_path == null)
      return "";

    try{
      File imgFile = new  File(_path);
      if(imgFile.exists()){
          Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
          int quality = 15;
  
          ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
          myBitmap.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream);
          byte[] byteArray = byteArrayOutputStream .toByteArray();
          long imgSize = byteArray.length/1024; //size in Kb
  
          while(imgSize > 50 && quality > 5){
              quality = quality - 5;
              myBitmap.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream);
              byteArray = byteArrayOutputStream .toByteArray();
              imgSize = byteArray.length/1024;
          }
      
          return Base64.encodeToString(byteArray, Base64.DEFAULT);
      }
    }catch(Exception exception){
      Log.d(LOG_TAG, exception.getMessage());
    }	  
	  
	  return "";	  
  }

  @ReactMethod
  private void searchFace(int typeDocument, String hash, String infoData, Callback callback){
    Activity currentActivity = getCurrentActivity();
    // Tim kiem khuon mat
    String rsSearchFace = "";
    rsSearchFace = SDKServiceUtils.searchFace(currentActivity, ACCESS_TOKEN, TOKEN_ID, TOKEN_KEY, "https://api.idg.vnpt.vn/face-service/v2/face/search", hash, UNIT);
    Log.d(LOG_TAG, "SDKServiceUtils " + rsSearchFace);
    JSONObject searchObj = null;
    try {
      searchObj = new JSONObject(rsSearchFace);    
      String msg = searchObj.getJSONObject("object").getString("msg");
      if("Unknown".equals(msg))  {
        Gson gson = new GsonBuilder().serializeNulls().create();
        CustomerInformation customerInformation = getObjectFromExtractInfo(typeDocument, infoData);
        customerInformation.setIpfs(hash);
        AddFaceRequest addFaceRequest = new AddFaceRequest();
        addFaceRequest.setCustomerInformation(customerInformation);
        addFaceRequest.setUnit(UNIT);
        //chuyển đổi thành string json
        String resultData = gson.toJson(addFaceRequest);
        Log.d(LOG_TAG, "searchFace resultData " + resultData);
        //chuyển đổi thành string base64
        String resultDataBase64 = Base64.encodeToString(resultData.getBytes(), Base64.DEFAULT);
        Log.d(LOG_TAG, "searchFace resultData Base64 " + resultDataBase64);
        searchObj.put("dataBase64Addface", resultDataBase64);
        searchObj.put("objectAddface", resultData);
      }
    } catch(Exception e)  {
      Log.d(LOG_TAG, "searchFace" + e.getMessage());
    }
    
    callback.invoke(searchObj.toString());

  }

  @ReactMethod
  private void addFace(int typeDocument, String hash, String checksum, String infoData, String resultObject, String resultDataBase64, Callback callback){
    Activity currentActivity = getCurrentActivity();
    // Add khuon mat
    Gson gson = new GsonBuilder().serializeNulls().create();
    //Ký dữ liệu lên chuỗi string base 64
    //String resultDataSign = signSHA1RSA(resultDataBase64);
    //chuyển đổi thành string json
    AddFaceRequest addFaceRequest = gson.fromJson(resultObject, AddFaceRequest.class);
    //thực hiện gọi add face
    String urlAddFace = "https://api.idg.vnpt.vn/face-service/v2/face/add";
    String rsAddFace = SDKServiceUtils.addFace(currentActivity, ACCESS_TOKEN, TOKEN_ID, TOKEN_KEY, urlAddFace, addFaceRequest, checksum, resultDataBase64);
    Log.d(LOG_TAG, "SDKServiceUtils " + rsAddFace);

    callback.invoke(rsAddFace);

  }

  /**
  * tiến hành fill dữ liệu ocr trả về vào CustomerInformation
  *
  * @param typeDocument : loại giấy tờ đang thực hiện ekyc
  * @param mExtractedInfo : dữ liệu ocr trả về
  * @return
  */
  private CustomerInformation getObjectFromExtractInfo(int typeDocument, String mExtractedInfo) {
      CustomerInformation mCustomerInfoEntity = new CustomerInformation();
      ExtraInfoObject extraInfoObject = new ExtraInfoObject();
      mCustomerInfoEntity.setExtra_info(extraInfoObject);
      Gson gson = new GsonBuilder().serializeNulls().create();
      if (typeDocument == 0 || typeDocument == SDKEnum.DocumentTypeEnum.IDENTITY_CARD.getValue()) {
          try {
              BaseResultResponse<IdentityCard> responseInfo = gson.fromJson(mExtractedInfo, new TypeToken<BaseResultResponse<IdentityCard>>() {
              }.getType());
              IdentityCard idCard = responseInfo.getObject();
              mCustomerInfoEntity.setCard_id(idCard.getId());
              mCustomerInfoEntity.setFullname(idCard.getName());
              mCustomerInfoEntity.setDob(idCard.getBirthDay());
              mCustomerInfoEntity.setGender(idCard.getGender());
              mCustomerInfoEntity.setAddress(idCard.getRecentLocation());
              mCustomerInfoEntity.setNationality(idCard.getNationality());
              mCustomerInfoEntity.setHometown(idCard.getOriginLocation());
          } catch (Exception e) {
              e.printStackTrace();
          }
      } else if (typeDocument == SDKEnum.DocumentTypeEnum.MILITARY_CARD.getValue()) {
          try {
              BaseResultResponse<IdentityCard> responseInfo = gson.fromJson(mExtractedInfo, new TypeToken<BaseResultResponse<IdentityCard>>() {
              }.getType());
              IdentityCard idCard = responseInfo.getObject();
              mCustomerInfoEntity.setMilitary_id(idCard.getId());
              mCustomerInfoEntity.setFullname(idCard.getName());
              mCustomerInfoEntity.setDob(idCard.getBirthDay());
              mCustomerInfoEntity.setGender(idCard.getGender());
              mCustomerInfoEntity.setAddress(idCard.getRecentLocation());
              mCustomerInfoEntity.setNationality(idCard.getNationality());
              mCustomerInfoEntity.setHometown(idCard.getOriginLocation());
          } catch (Exception e) {
              e.printStackTrace();
          }
      } else if (typeDocument == SDKEnum.DocumentTypeEnum.PASSPORT.getValue()) {
          try {
              BaseResultResponse<Passport> responseInfo = gson.fromJson(mExtractedInfo, new TypeToken<BaseResultResponse<Passport>>() {
              }.getType());
              Passport passport = responseInfo.getObject();
              mCustomerInfoEntity.setCard_id(passport.getId());
              mCustomerInfoEntity.setPassport_id(passport.getPassport_no());
              mCustomerInfoEntity.setFullname(passport.getName());
              mCustomerInfoEntity.setDob(passport.getBirth_day());
              mCustomerInfoEntity.setGender(passport.getGender());
              mCustomerInfoEntity.setHometown(passport.getBirth_place());
              mCustomerInfoEntity.setNationality(passport.getNationality());
          } catch (Exception e) {
              e.printStackTrace();
          }
      } else if (typeDocument == SDKEnum.DocumentTypeEnum.DRIVER_LICENSE.getValue()) {
          try {
              BaseResultResponse<DriverLicense> responseInfo = gson.fromJson(mExtractedInfo, new TypeToken<BaseResultResponse<DriverLicense>>() {
              }.getType());
              DriverLicense driverLicense = responseInfo.getObject();
              mCustomerInfoEntity.setDriver_license_id(driverLicense.getId());
              mCustomerInfoEntity.setFullname(driverLicense.getName());
              mCustomerInfoEntity.setDob(driverLicense.getBirthDay());
              mCustomerInfoEntity.setGender(driverLicense.getGender());
              mCustomerInfoEntity.setHometown(driverLicense.getRecentLocation());
              mCustomerInfoEntity.setNationality(driverLicense.getNationality());
          } catch (Exception e) {
              e.printStackTrace();
          }
      }

      return mCustomerInfoEntity;
  }
}