/*-
 * ~~~~~~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.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

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

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

import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceProcessor;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.JSONUtils;
import ru.entaxy.platform.base.support.osgi.OSGIUtils;
import ru.entaxy.security.keystore.runtime.EntaxyKeystore;
import ru.entaxy.security.keystore.runtime.internal.KeystoreProcessorHelper.KeyData;

public class JWKResourceProcessor implements EntaxyResourceProcessor {

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

    @Override
    public InputStream preProcess(InputStream origin, EntaxyResource resource) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void postProcess(EntaxyResource resource) {
        if (!resource.exists())
            return;
        if (!resource.getName().endsWith(".".concat(EntaxyKeystore.KEYSTORE_TYPE_JWK)))
            return;

        KeystoreProcessorHelper helper = new KeystoreProcessorHelper(resource);

        helper.reset();
        helper.clearData();
        helper.setKeystoreType(EntaxyKeystore.KEYSTORE_TYPE_JWK);
        helper.update();

        try {

            EntaxyResourceService entaxyResourceService =
                    OSGIUtils.services().ofClass(EntaxyResourceService.class).waitService(10000).get();

            helper.setResourceService(entaxyResourceService);

            JsonArray ja =
                    JSONUtils.getJsonRootObject(resource.getAsString()).getAsJsonObject()
                            .get(EntaxyKeystore.JWK_PROP_KEYS).getAsJsonArray();

            List<KeyData> keyDataList = new ArrayList<>();
            for (int i = 0; i < ja.size(); i++) {
                JsonElement je = ja.get(i);
                if (!je.isJsonObject())
                    continue;
                JsonObject jo = je.getAsJsonObject();
                if (!jo.has(EntaxyKeystore.JWK_PROP_KID))
                    continue;
                try {
                    String kid = jo.get(EntaxyKeystore.JWK_PROP_KID).getAsString();
                    KeyData keyData = new KeyData();
                    keyData.alias = kid;
                    keyDataList.add(keyData);
                } catch (Exception ignore) {
                    // NOOP
                }
            }
            helper.setKeys(keyDataList);

            helper.createKeysResources();

            helper.setValid();

        } catch (Exception e) {
            // something's wrong: log exception and clear metadata
            LOG.error("Erorr in JWK postProcess", e);
            helper.setKeys(Collections.emptyList());
            helper.setValid(false);
        }

        helper.setProcessed();

        helper.update();

    }

}
