/*-
 * ~~~~~~licensing~~~~~~
 * jaas-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.platform.runtime.security.jaas;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.security.auth.login.AppConfigurationEntry;

import org.apache.karaf.jaas.boot.ProxyLoginModule;
import org.apache.karaf.jaas.config.JaasRealm;
import org.apache.karaf.jaas.modules.BackingEngine;
import org.apache.karaf.jaas.modules.BackingEngineFactory;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;

import ru.entaxy.platform.base.support.CommonUtils;

@Component(service = JaasHelper.class, immediate = true)
public class JaasHelper {

    static private JaasHelper INSTANCE;

    static public JaasHelper getInstance() {
        return INSTANCE;
    }

    @Activate
    public void activate() {
        INSTANCE = this;
    }

    @Reference(cardinality = ReferenceCardinality.MULTIPLE,
            policyOption = ReferencePolicyOption.GREEDY)
    List<BackingEngineFactory> engineFactories;

    Map<String, List<JaasRealm>> realms = new HashMap<>();

    Object realmsLock = new Object();

    @Reference(cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY,
            policy = ReferencePolicy.DYNAMIC, unbind = "unbindRealm")
    public void bindRealm(JaasRealm realm) {
        synchronized (realmsLock) {
            if (!realms.containsKey(realm.getName()))
                realms.put(realm.getName(), new ArrayList<>());
            List<JaasRealm> list = realms.get(realm.getName());
            if (!list.contains(realm))
                list.add(realm);
            Collections.sort(list, new Comparator<JaasRealm>() {

                @Override
                public int compare(JaasRealm o1, JaasRealm o2) {

                    // sort in reverse order: max is the first, min is the last

                    if (o1.getRank() > o2.getRank())
                        return -1;
                    if (o1.getRank() < o2.getRank())
                        return 1;
                    return 0;
                }
            });
            realms.put(realm.getName(), list);

        }
    }

    public void unbindRealm(JaasRealm realm) {
        synchronized (realmsLock) {
            if (!realms.containsKey(realm.getName()))
                return;
            realms.get(realm.getName()).remove(realm);
        }
    }

    public JaasRealm getRealm(String name) {
        if (!realms.containsKey(name))
            return null;
        List<JaasRealm> list = realms.get(name);
        if (list.isEmpty())
            return null;
        return list.get(0);
    }

    public AppConfigurationEntry getEntry(String realmName, String moduleName) {
        JaasRealm realm = getRealm(realmName);
        if (realm == null)
            return null;
        AppConfigurationEntry[] entries = realm.getEntries();
        if (entries == null)
            return null;
        for (AppConfigurationEntry entry : entries) {
            String entaxyId = (String) entry.getOptions().get("entaxy.id");
            if (!CommonUtils.isValid(entaxyId))
                continue;
            if (entaxyId.trim().equals(moduleName))
                return entry;
        }
        return null;
    }

    public BackingEngine getBackingEngine(String realmName, String moduleName) {
        AppConfigurationEntry entry = getEntry(realmName, moduleName);
        if (entry == null)
            return null;
        for (BackingEngineFactory factory : engineFactories) {
            String loginModuleClass = (String) entry.getOptions().get(ProxyLoginModule.PROPERTY_MODULE);
            if (factory.getModuleClass().equals(loginModuleClass)) {
                return factory.build(entry.getOptions());
            }
        }
        return null;
    }
}
