/*-
 * ~~~~~~licensing~~~~~~
 * data-mapper-management
 * ==========
 * 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.modules.data.datamapper.management.impl;

import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.esb.platform.base.management.core.ManagementCore;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean;
import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean;
import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanFactory;
import ru.entaxy.platform.core.management.object.MBeanFactory;
import ru.entaxy.platform.core.management.object.factory.AbstractMBeanFactory;
import ru.entaxy.platform.modules.data.datamapper.management.AbstractDataMapperMBean;
import ru.entaxy.platform.modules.data.datamapper.management.EmbeddedDataMapperMBean;
import ru.entaxy.platform.modules.datamapper.DataMapper;
import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject;

@MBeanFactory(id = "data-mapper-factory", supportedTypes = {"entaxy.runtime.data-mapper"})
@Component(service = {EntaxyRuntimeObjectMBeanFactory.class},
        immediate = true)
public class DataMapperMBeanFactory extends AbstractMBeanFactory {

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

    protected BundleContext bundleContext;

    @Activate
    public DataMapperMBeanFactory(BundleContext bundleContext) {
        super();
        this.bundleContext = bundleContext;
    }

    // @Activate
    public void activate(ComponentContext componentContext) {
        this.bundleContext = componentContext.getBundleContext();
    }

    @Override
    public <T extends EntaxyRuntimeObjectMBean> T createMBean(EntaxyRuntimeObject entaxyRuntimeObject) {
        return null;
    }

    @Override
    public List<? extends EntaxyRuntimeItemMBean> createMBeans() {
        return Collections.emptyList();
    }

    // embedded mappers (e.g. entaxy-default) processing

    protected Map<DataMapper, EmbeddedDataMapperRegistration> embedded = Collections.synchronizedMap(new HashMap<>());

    @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC,
            policyOption = ReferencePolicyOption.GREEDY, target = "(isEntaxyEmbedded=true)",
            unbind = "removeEmbeddedMapper")
    public void addEmbeddedMapper(DataMapper dataMapper) {
        try {
            EmbeddedDataMapperRegistration registration = new EmbeddedDataMapperRegistration();
            registration.register(dataMapper);
            this.embedded.put(dataMapper, registration);
        } catch (Exception e) {
            LOG.error(String.format("Error registering MBean for DataMapper: [%s]", dataMapper.getId()), e);
        }
    }

    public void removeEmbeddedMapper(DataMapper dataMapper) {
        try {
            EmbeddedDataMapperRegistration registration = embedded.get(dataMapper);
            if (registration != null)
                registration.unregister();
            this.embedded.remove(dataMapper);
        } catch (Exception e) {
            LOG.error(String.format("Error unregistering MBean for DataMapper: [%s]", dataMapper.getId()), e);
        }

    }

    protected class EmbeddedDataMapperRegistration {

        ServiceRegistration<EmbeddedDataMapperMBean> registration;

        EmbeddedDataMapperMBeanImpl bean;

        protected void register(DataMapper dataMapper) throws Exception {
            bean = new EmbeddedDataMapperMBeanImpl(dataMapper);
            Hashtable<String, String> props = new Hashtable<>();
            props.put(ManagementCore.JMX_OBJECTNAME,
                    AbstractDataMapperMBean.getQualifier(dataMapper.getId()).getValue());
            // catch and ignore exception typical for bundle refreshing process
            try {
                this.registration = bundleContext.registerService(EmbeddedDataMapperMBean.class, bean, props);
            } catch (IllegalStateException e) {
                if (!CommonUtils.isValid(e.getMessage()) || !e.getMessage().contains("Invalid BundleContext"))
                    throw e;
            }
        }

        protected void unregister() {
            try {
                this.registration.unregister();
            } catch (Exception ignore) {
                // noop
            }
        }

    }

}
