package com.fastest.pass.app

import android.util.Base64
import android.util.Log
import com.fastest.pass.login.data.model.UserInfo
import java.security.MessageDigest
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

class Utils {
    companion object {

        fun hashing_sha256(text: String): String {
            val bytes = MessageDigest.getInstance("SHA-256").digest(text.toByteArray())
            return bytes.joinToString("") { "%02x".format(it) }
        }

        fun sha256(input: String): String {
            val bytes = MessageDigest.getInstance("SHA-256").digest(input.toByteArray())
            return bytes.joinToString("") { "%02x".format(it) }
        }

        fun generateKey() : SecretKey {
            val keyGen = KeyGenerator.getInstance("AES")
            keyGen.init(256)
            return keyGen.generateKey()
        }

        fun encryptData(
            data: String,
            secretKeyString: String,
            ivString: String,
            saltString: String
        ) : Pair<String, String> {
            val ivKey: IvParameterSpec = IvParameterSpec(ivString.toByteArray(Charsets.UTF_8))
            val secKey: SecretKey = SecretKeySpec(secretKeyString.toByteArray(Charsets.UTF_8), "AES")
            val encryptionWithSalt = saltString.toByteArray(Charsets.UTF_8) + data.toByteArray(Charsets.UTF_8)

            val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
            cipher.init(Cipher.ENCRYPT_MODE, secKey, ivKey)

            val encryptedData = cipher.doFinal(data.toByteArray())

//    val encryptedData = cipher.doFinal(data.toByteArray())
            val ivBase64 = Base64.encodeToString(ivString.toByteArray(Charsets.UTF_8), Base64.DEFAULT)
            val encryptedDataBase64 = Base64.encodeToString(encryptedData, Base64.DEFAULT)

            return Pair(ivBase64, encryptedDataBase64)
        }

        fun decryptData(ivBase64: String, encryptedBase64: String, secretKeyString: String) : String {
            val iv = Base64.decode(ivBase64, Base64.DEFAULT)
            val encryptedBytes = Base64.decode(encryptedBase64, Base64.DEFAULT)
            val ivSpec = IvParameterSpec(iv)
            val secKey: SecretKey = SecretKeySpec(secretKeyString.toByteArray(Charsets.UTF_8), "AES")

            val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
            cipher.init(Cipher.DECRYPT_MODE, secKey, ivSpec)

            val decryptedData = cipher.doFinal(encryptedBytes)
            val decryptedString = String(decryptedData, Charsets.UTF_8)

            return decryptedString
        }

        fun customSaltKey(userinfo: UserInfo) : String {
            val id = userinfo.id
            val email = userinfo.email
            val saltKey = "${id}_${email}_${id}"
            val filterSaltKey = saltKey.replace("[@.]".toRegex(), "")
            return filterSaltKey
        }
    }
}