/*-
 * ~~~~~~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.internal;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceMetadata;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.JSONUtils;
import ru.entaxy.security.keystore.runtime.EntaxyKeystore;

public class KeystoreProcessorHelper {

    private static final Logger LOG = LoggerFactory.getLogger(KeystoreProcessorHelper.class);

    public static class KeyData {
        public String alias;
    }

    EntaxyResource entaxyResource;

    String dataFolderLocation;

    EntaxyResourceMetadata meta;
    EntaxyResourceMetadata.MetadataSection section;

    JsonObject sectionContent;

    EntaxyResourceService resourceService;

    List<KeyData> keys;

    public KeystoreProcessorHelper(EntaxyResource entaxyResource) {
        super();
        this.entaxyResource = entaxyResource;
        this.dataFolderLocation = this.entaxyResource.getURL().concat(".data");
        this.meta = this.entaxyResource.getMetadata(true);
        this.section = this.meta.getSection(EntaxyKeystore.KEYSTORE_META_SECTION_NAME);
        this.sectionContent = this.section.getContent();
    }

    public void reset() {
        setProcessed(false);
    }

    public void clearData() {
        if (resourceService == null)
            return;
        resourceService.getResource(dataFolderLocation).delete();
    }

    public void createKeysResources() {
        if (this.keys == null)
            return;
        for (KeyData keyData : this.keys)
            createKeyResources(keyData);
    }

    protected void createKeyResources(KeyData keyData) {
        StringBuffer propertiesData = new StringBuffer("rs.security.keystore.alias=");
        propertiesData.append(keyData.alias).append("\n");

        if (resourceService == null) {
            LOG.error("Can't create resources for alias [%s]: resourceService not set", keyData.alias);
            return;
        }

        String keyResourcePropertiesLocation =
                dataFolderLocation.concat("/").concat(keyData.alias).concat(".data");
        EntaxyResource keyPropertiesData = resourceService.getResource(keyResourcePropertiesLocation);
        try (InputStream is = new ByteArrayInputStream(propertiesData.toString().getBytes())) {
            keyPropertiesData.save(is);
        } catch (Exception e) {
            LOG.error(String.format("Error saving resource: [%s]", keyResourcePropertiesLocation), e);
            return;
        }

        String keyPropertiesLocation =
                dataFolderLocation.concat("/$").concat(keyData.alias).concat(".properties");
        EntaxyResource keyProperties = resourceService.getResource(keyPropertiesLocation);
        JsonObject jo = new JsonObject();
        JSONUtils.JsonBuilder.create(jo).object("@SEQUENCE", true)
                .string("delimiter", "__LF__")
                .array("items")
                .object()
                .string("url",
                        entaxyResource.getURL().substring(0, entaxyResource.getURL().lastIndexOf('.'))
                                .concat(".properties"))
                .bool("required", true)
                .up()
                .object()
                .string("url", keyResourcePropertiesLocation)
                .bool("required", true)
                .up();

        try (InputStream is = new ByteArrayInputStream(jo.toString().getBytes())) {
            keyProperties.save(is);
        } catch (Exception e) {
            LOG.error(String.format("Error saving resource: [%s]", keyPropertiesLocation), e);
            return;
        }

        JSONUtils.replaceValue(
                keyProperties.getMetadata(true).getSection(EntaxyResourceMetadata.SECTION_RESOURCE.NAME).getContent(),
                "@SEQUENCE",
                jo.get("@SEQUENCE"));
        keyProperties.getMetadata().update();
        update();
    }

    public EntaxyResourceService getResourceService() {
        return resourceService;
    }

    public void setResourceService(EntaxyResourceService resourceService) {
        this.resourceService = resourceService;
    }

    public void setKeystoreType(String keystoreType) {
        if (sectionContent.has(EntaxyKeystore.KEYSTORE_META_PROP_TYPE))
            sectionContent.remove(EntaxyKeystore.KEYSTORE_META_PROP_TYPE);
        sectionContent.addProperty(EntaxyKeystore.KEYSTORE_META_PROP_TYPE, keystoreType);
    }

    public void setKeys(List<KeyData> keys) {
        this.keys = keys;
        sectionContent.remove(EntaxyKeystore.KEYSTORE_META_PROP_ALIASES);
        sectionContent.add(EntaxyKeystore.KEYSTORE_META_PROP_ALIASES, getAliasesArray());
    }

    protected JsonArray getAliasesArray() {
        JsonArray result = new JsonArray();
        if (this.keys != null)
            for (KeyData data : this.keys)
                result.add(data.alias);
        return result;
    }

    public void setValid() {
        setValid(true);
    }

    public void setValid(boolean isValid) {
        sectionContent.remove(EntaxyKeystore.KEYSTORE_META_PROP_VALID);
        sectionContent.addProperty(EntaxyKeystore.KEYSTORE_META_PROP_VALID, isValid);
    }

    public void setProcessed() {
        setProcessed(true);
    }

    public void setProcessed(boolean isProcessed) {
        sectionContent.remove(EntaxyKeystore.KEYSTORE_META_PROP_PROCESSED);
        sectionContent.addProperty(EntaxyKeystore.KEYSTORE_META_PROP_PROCESSED, isProcessed);
    }

    public void update() {
        meta.update();
    }

}
