package kr.lunaticbum.back.lun.utils

import com.google.gson.Gson
import kr.lunaticbum.back.lun.model.RequestModel
import java.util.Base64

//
//
//import javax.crypto.Cipher
//import org.apache.commons.codec.DecoderException;
//import org.apache.commons.codec.binary.Base64;
//import org.apache.commons.codec.binary.Hex;
//
//@Throws(Exception::class)
//fun AesECBEncode(plainText: String): String {
//    //Cipher 객체 인스턴스화(Java에서는 PKCS#5 = PKCS#7이랑 동일)
//
//    val c: Cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
//
//
//    //Cipher 객체 초기화
//    c.init(Cipher.ENCRYPT_MODE, secretKey)
//
//
//    //Encrpytion/Decryption
//    val encrpytionByte: ByteArray = c.doFinal(plainText.toByteArray(charset("UTF-8")))
//
//
//    //Hex Encode
//    return Hex.encodeHexString(encrpytionByte)
//
//
//    //Base64 Encode
////		return Base64.encodeBase64String(encrpytionByte);
//}
//
//
////AES ECB PKCS5Padding 복호화(Hex | Base64)
//@Throws(Exception::class)
//fun AesECBDecode(encodeText: String): String {
//    //Cipher 객체 인스턴스화(Java에서는 PKCS#5 = PKCS#7이랑 동일)
//
//    val c: Cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
//
//
//    //Cipher 객체 초기화
//    c.init(Cipher.DECRYPT_MODE, secretKey)
//
//
//    //Decode Hex
//    val decodeByte: ByteArray = Hex.decodeHex(encodeText.toCharArray())
//
//
//    //Decode Base64
////		byte[] decodeByte = Base64.decodeBase64(encodeText);
//    return String(c.doFinal(decodeByte), charset("UTF-8"))
//}
fun String.plainText() = String(Base64.getMimeDecoder().decode(this))

fun String.extractModelData(calback : (Exception?,String)->Unit) {
    try {
        val decodedBytes: ByteArray = Base64.getDecoder().decode(this)
        String(decodedBytes).let { resultString ->
            try {
                Gson().fromJson<RequestModel>(resultString, RequestModel::class.java).let { model ->
                    model.data?.let { jsonString ->
                        try {
                            println("RequestModel ${jsonString}")
                            calback.invoke(null,model.extractData())
                        } catch (e: Exception) {
                            calback.invoke(ExtractDataRequestModelException("Exception on extractData with ${Gson().toJson(model)}", e.cause), jsonString)
                        }
                    }
                }
            } catch (e: Exception) {
                calback.invoke(MakeRequestModelException("Exception on make RequestModel with $resultString", e.cause),this@extractModelData)
            }
        }
    } catch (e: Exception) {
        calback.invoke(Base64DecodeException("Exception on Base64 decode", e.cause),this@extractModelData)
    }
}
class Base64DecodeException(message: String, cause : Throwable? = null) : Exception(message, cause)
class MakeRequestModelException(message: String, cause : Throwable? = null) : Exception(message, cause)
class ExtractDataRequestModelException(message: String, cause : Throwable? = null) : Exception(message, cause)