/*-
 * ~~~~~~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.filter;

import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;

import org.osgi.service.event.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.audit.service.AuditService;

public class EventRouter {
    private final Queue<Event> events = new LinkedBlockingQueue<>(10_000);
    private final AtomicLong counter = new AtomicLong(0);
    private final AtomicLong consumed = new AtomicLong(0);
    private final AtomicLong rejected = new AtomicLong(0);
    private final ExecutorService executor = Executors.newFixedThreadPool(3,
            (r) -> new Thread(r, "audit-logger-helper-thread #" + counter.getAndIncrement()));
    private final AuditService auditService;

    private static final Logger LOGGER = LoggerFactory.getLogger(EventRouter.class);

    public EventRouter(AuditService service) {
        this.auditService = service;
    }

    private boolean processEvent(Event event) {
        if (event == null) {
            return false;
        }
        if (event.getTopic().contains("EXECUTED") && event.getProperty("command") != null) {
            auditService.onOSGIEvent(event);
            return true;
        } else {
            // if it's a log event
            if (event.getTopic().startsWith("org/osgi/service/log")) {
                String bundleSymbolicName = (String) event.getProperty("bundle.symbolicname");
                // if it's configuration update event
                if (bundleSymbolicName != null && "org.apache.felix.fileinstall".equals(bundleSymbolicName)) {
                    Object message = event.getProperty("message");
                    if (message instanceof String) {
                        String messageText = (String) message;
                        if (messageText.contains("Updating")) {
                            auditService.onFileChange(event);
                            return true;
                        }
                    }
                }
            } else {
                return auditService.interpret(event);
            }
        }
        return false;
    }

    public String stats() {
        return String.format("Consumed: %d, rejected: %d", consumed.get(), rejected.get());
    }

    public void consumeEvent(Event event) {
        boolean added = events.offer(event);
        if (added) {
            executor.submit(() -> {
                Event evt = events.poll();
                if (processEvent(evt)) {
                    consumed.incrementAndGet();
                } else {
                    rejected.incrementAndGet();
                }
            });
        } else {
            LOGGER.warn("Cannot consume event {}, queue is probably full", event);
        }
    }

    public void stop() {
        executor.shutdown();
        events.clear();
    }
}
