/*-
 * ~~~~~~licensing~~~~~~
 * entaxy-audit
 * ==========
 * 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.audit.service.jmx;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.event.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.audit.service.EventInterpreter;
import ru.entaxy.audit.service.InterpretedEvent;
import ru.entaxy.audit.service.InterpretedEvent.EventResolution;

@Component(service = EventInterpreter.class, immediate = true, configurationPid = "ru.entaxy.audit.interpreter.jmx",
        configurationPolicy = ConfigurationPolicy.OPTIONAL)
public class JMXEventInterpreter implements EventInterpreter {

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

    public static final String JMX_AUDIT_TOPIC_PREFIX = "javax/management/MBeanServer";

    public static final String JMX_AUDIT_INVOKE_SUBTOPIC = "INVOKE";

    protected static final String PROP_IGNORE_TOPICS = "topics.ignore";

    protected static final String PROP_PROCESS_TOPICS = "topics.process";

    protected List<String> topicsToIgnore = new ArrayList<>();

    protected List<String> topicsToProcess = new ArrayList<>();

    @Activate
    public void activate(Map<String, Object> properties) {
        parseProperties(properties);
    }

    @Modified
    public void modified(Map<String, Object> properties) {
        parseProperties(properties);
    }

    protected void parseProperties(Map<String, Object> properties) {
        if (properties == null)
            return;
        if (LOG.isDebugEnabled())
            LOG.debug("\n CONFIGURATION :: \n " + properties.toString());
        if (properties.containsKey(PROP_IGNORE_TOPICS)) {
            String ignoreTopics = (String) properties.get(PROP_IGNORE_TOPICS);
            if (ignoreTopics == null)
                topicsToIgnore = new ArrayList<>();
            else {
                topicsToIgnore = Arrays.asList(ignoreTopics.split(","));
            }
        } else {
            topicsToIgnore = new ArrayList<>();
        }
        if (properties.containsKey(PROP_PROCESS_TOPICS)) {
            String processTopics = (String) properties.get(PROP_PROCESS_TOPICS);
            if (processTopics == null)
                topicsToProcess = new ArrayList<>();
            else {
                topicsToProcess = Arrays.asList(processTopics.split(","));
            }
        } else {
            topicsToProcess = new ArrayList<>();
        }

    }

    @Override
    public InterpretedEvent interpret(Event origin) {
        if (!origin.getTopic().startsWith(JMX_AUDIT_TOPIC_PREFIX))
            return null;

        JMXInterpretedEvent result;

        String subtopic = origin.getTopic().substring(JMX_AUDIT_TOPIC_PREFIX.length() + 1);

        if (subtopic.startsWith(JMX_AUDIT_INVOKE_SUBTOPIC))
            result = new JMXInvokeEvent(origin);
        else
            result = new JMXInterpretedEvent(origin);

        result.subtopic = subtopic;

        result.resolution = EventResolution.IGNORE;

        if (!topicsToProcess.isEmpty()) {
            for (String process : topicsToProcess)
                if (result.subtopic.startsWith(process)) {
                    result.resolution = EventResolution.PROCESS;
                    break;
                }

        } else {
            result.resolution = EventResolution.PROCESS;
        }

        for (String ignore : topicsToIgnore)
            if (result.subtopic.startsWith(ignore)) {
                result.resolution = EventResolution.IGNORE;
                break;
            }

        return result;
    }


}
