/**
 * ProjectLaogai
 *
 * Copyright 2019-2020  <seil0@mosad.xyz>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 */

package org.mosad.seil0.projectlaogai.controller.preferences

import android.content.Context
import android.content.SharedPreferences
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Log
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
import org.mosad.seil0.projectlaogai.R

object EncryptedPreferences {

    var email = ""
        internal set

    /**
     * save user email and password to encrypted preference
     */
    fun saveCredentials(email: String, password: String, context: Context) {
        this.email = email

        with (getEncryptedPreferences(context)?.edit()) {
            this?.putString(context.getString(R.string.save_key_user_email), email)
            this?.putString(context.getString(R.string.save_key_user_password), password)
            this?.apply()
        }

    }

    /**
     * read user email and password from encrypted preference
     * @return Pair(email, password)
     */
    fun readCredentials(context: Context): Pair<String, String> {
        return with (getEncryptedPreferences(context)) {
            email = this?.getString(context.getString(R.string.save_key_user_email), "").toString()

            Pair(
                this?.getString(context.getString(R.string.save_key_user_email), "").toString(),
                this?.getString(context.getString(R.string.save_key_user_password), "").toString()
            )
        }
    }

    /**
     * initially load the stored values
     */
    fun load(context: Context) {
        with(getEncryptedPreferences(context)) {
            email = this?.getString(
                context.getString(R.string.save_key_user_email), ""
            ).toString()
        }
    }

    /**
     * create a encrypted shared preference
     */
    private fun getEncryptedPreferences(context: Context): SharedPreferences? {
        return try {
            val spec = KeyGenParameterSpec.Builder(MasterKey.DEFAULT_MASTER_KEY_ALIAS,
                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                .setKeySize(MasterKey.DEFAULT_AES_GCM_MASTER_KEY_SIZE)
                .build()

            val masterKey = MasterKey.Builder(context)
                .setKeyGenParameterSpec(spec)
                .build()

            EncryptedSharedPreferences.create(
                context,
                context.getString(R.string.encrypted_preference_file_key),
                masterKey,
                EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
                EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
            )
        } catch (ex: Exception) {
            Log.e(javaClass.name, "Could not create encrypted shared preference.", ex)
            null
        }
    }



}