/*-
 * ~~~~~~licensing~~~~~~
 * route-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.core.management.route.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.management.NotCompliantMBeanException;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean;
import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean;
import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanCustomizer;
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.core.management.route.RoutesMBean;
import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject;

@MBeanFactory(id = "route-factory", supportedTypes = {"entaxy.runtime.route-library", "entaxy.runtime.route"})
@Component(service = {EntaxyRuntimeObjectMBeanFactory.class, EntaxyRuntimeObjectMBeanCustomizer.class},
        immediate = true)
public class RouteMbeanFactory extends AbstractMBeanFactory implements EntaxyRuntimeObjectMBeanCustomizer {

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

    protected static String ROUTE_TYPE = "entaxy.runtime.route";
    protected static String ROUTE_LIBRARY_TYPE = "entaxy.runtime.route-library";

    protected static String ROUTE_CONTAINER_MARKER = "isRouteContainer";

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    RouteLibrariesMBeanImpl routeLibrariesMBean;

    @Override
    public <T extends EntaxyRuntimeObjectMBean> T createMBean(EntaxyRuntimeObject entaxyRuntimeObject) {

        EntaxyRuntimeObjectMBean bean = null;

        if (entaxyRuntimeObject.getType().equals(ROUTE_TYPE)
                || entaxyRuntimeObject.getType().startsWith(ROUTE_TYPE + ".")) {
            try {
                bean = new RouteMBeanImpl(entaxyRuntimeObject);
            } catch (Exception e) {
                LOG.error("Error creating RouteMBeanImpl", e);
            }
        } else if (entaxyRuntimeObject.getType().equals(ROUTE_LIBRARY_TYPE)
                || entaxyRuntimeObject.getType().startsWith(ROUTE_LIBRARY_TYPE)) {
            try {
                bean = new RouteLibraryMBeanImpl(entaxyRuntimeObject);
                bean.setParentMBean(routeLibrariesMBean);
            } catch (Exception e) {
                LOG.error("Error creating RouteLibraryMBeanImpl", e);
            }
        }
        return (T) bean;
    }

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

    /* EntaxyRuntimeObjectMBeanCustomizer */

    @Override
    public boolean isAccepted(EntaxyRuntimeObjectMBean bean) {
        boolean result = false;
        try {
            result = Boolean.parseBoolean(
                    bean.getRuntimeObject().getAttributeOrDefault(ROUTE_CONTAINER_MARKER, "false").toString());
        } catch (Exception ignore) {
            // NOOP
        }
        return result;
    }

    @Override
    public Customized customize(EntaxyRuntimeObjectMBean bean) {
        CustomizedImpl result = new CustomizedImpl();
        result.mBean = bean;

        try {
            RoutesMBeanImpl routesMBeanImpl = new RoutesMBeanImpl(bean.getRuntimeObject());
            routesMBeanImpl.setParentMBean(bean);
            result.additionalMBeans.add(routesMBeanImpl);
        } catch (NotCompliantMBeanException e) {
            LOG.error(String.format("Error creating customized bean [%s] for [%s]", RoutesMBean.class.getName(),
                    bean.getRuntimeObject()), e);
        }

        return result;
    }

    protected static class CustomizedImpl implements Customized {

        EntaxyRuntimeObjectMBean mBean;

        List<EntaxyRuntimeObjectMBean> additionalMBeans = new ArrayList<>();

        @Override
        public EntaxyRuntimeObjectMBean getCustomizedMBean() {
            return mBean;
        }

        @Override
        public List<EntaxyRuntimeObjectMBean> getAdditionalMBeans() {
            return additionalMBeans;
        }

    }

}
