/*-
 * ~~~~~~licensing~~~~~~
 * keystore-runtime
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.security.keystore.runtime.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.base.support.JSONUtils;
import ru.entaxy.security.keystore.runtime.EntaxyKeystore;
import ru.entaxy.security.keystore.runtime.EntaxyKeystoreCausedException;
import ru.entaxy.security.keystore.runtime.EntaxyKeystoreException;
import ru.entaxy.security.keystore.runtime.UnsupportedKeyFormatException;

public class JWKKeystoreHelper extends KeystoreHelper {

    @Override
    public void addKey(String alias, String keyContent) throws EntaxyKeystoreException {
        JsonObject jo = null;
        try {
            jo = JSONUtils.getJsonRootObjectUnsafe(keyContent);
        } catch (Exception e) {
            throw new UnsupportedKeyFormatException(keystoreResource.keystoreId, keyContent);
        }

        // TODO check content

        if (CommonUtils.isValid(alias)) {
            if (jo.has(EntaxyKeystore.JWK_PROP_KID))
                jo.remove(EntaxyKeystore.JWK_PROP_KID);
            jo.addProperty(EntaxyKeystore.JWK_PROP_KID, alias);
        }

        JsonObject keystoreContent = JSONUtils.getJsonRootObject(keystoreResource.entaxyResource.getAsString());
        if (!keystoreContent.has(EntaxyKeystore.JWK_PROP_KEYS))
            keystoreContent.add(EntaxyKeystore.JWK_PROP_KEYS, new JsonArray());
        JsonElement keys = keystoreContent.get(EntaxyKeystore.JWK_PROP_KEYS);
        if (!keys.isJsonArray()) {
            keystoreContent.remove(EntaxyKeystore.JWK_PROP_KEYS);
            keystoreContent.add(EntaxyKeystore.JWK_PROP_KEYS, new JsonArray());
        }
        JsonArray keysArray = keystoreContent.get(EntaxyKeystore.JWK_PROP_KEYS).getAsJsonArray();
        keysArray.add(jo);

        try (InputStream is = new ByteArrayInputStream(keystoreContent.toString().getBytes())) {
            updateKeystore(is);
        } catch (Exception e) {
            throw new EntaxyKeystoreCausedException(keystoreResource.keystoreId, e);
        }
    }

    @Override
    public void removeKey(String alias) throws EntaxyKeystoreException {

        if (!CommonUtils.isValid(alias))
            return;

        JsonObject keystoreContent = JSONUtils.getJsonRootObject(keystoreResource.entaxyResource.getAsString());
        if (!keystoreContent.has(EntaxyKeystore.JWK_PROP_KEYS))
            return;

        JsonElement keys = keystoreContent.get(EntaxyKeystore.JWK_PROP_KEYS);
        if (!keys.isJsonArray()) {
            return;
        }
        JsonArray keysArray = keystoreContent.get(EntaxyKeystore.JWK_PROP_KEYS).getAsJsonArray();
        JsonArray newKeysArray = new JsonArray();

        for (JsonElement item : keysArray) {
            if (!item.isJsonObject()) {
                // item is invalid, but we just keep it
                newKeysArray.add(item);
                continue;
            }

            JsonObject itemObject = item.getAsJsonObject();
            if (!itemObject.has(EntaxyKeystore.JWK_PROP_KID)) {
                // item is invalid, but we just keep it
                newKeysArray.add(item);
                continue;
            }

            try {
                String itemKid = itemObject.get(EntaxyKeystore.JWK_PROP_KID).getAsString();
                if (!alias.equals(itemKid)) {
                    newKeysArray.add(item);
                }
            } catch (Exception ignore) {
                newKeysArray.add(item);
                continue;
            }
        }

        JSONUtils.replaceValue(keystoreContent, EntaxyKeystore.JWK_PROP_KEYS, newKeysArray);

        try (InputStream is = new ByteArrayInputStream(keystoreContent.toString().getBytes())) {
            updateKeystore(is);
        } catch (Exception e) {
            throw new EntaxyKeystoreCausedException(keystoreResource.keystoreId, e);
        }

    }

}
