/*-
 * ~~~~~~licensing~~~~~~
 * cluster-persistence-service
 * ==========
 * 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~~~~~~
 */
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package ru.entaxy.esb.platform.core.cluster.persistence.handler;

import org.apache.karaf.cellar.core.event.Event;
import org.apache.karaf.cellar.core.event.EventHandler;
import org.apache.karaf.cellar.core.event.EventHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Event dispatcher task.
 */
public class LocalEventDispatchTask<E extends Event> implements Runnable {

    private static final transient Logger LOGGER = LoggerFactory.getLogger(LocalEventDispatchTask.class);
    private static final long DEFAULT_TIMEOUT = 30000;

    private E event;
    private EventHandlerRegistry handlerRegistry;
    private long timeout;
    private long interval = 1000;

    public LocalEventDispatchTask(E event, EventHandlerRegistry handlerRegistry) {
        this.event = event;
        this.handlerRegistry = handlerRegistry;
        if (System.getProperty("cellar.timeout") != null) {
            try {
                this.timeout = Long.parseLong(System.getProperty("cellar.timeout"));
            } catch (Exception e) {
                this.timeout = DEFAULT_TIMEOUT;
            }
        } else {
            this.timeout = DEFAULT_TIMEOUT;
        }
    }

    public LocalEventDispatchTask(E event, EventHandlerRegistry handlerRegistry, long timeout) {
        this.event = event;
        this.handlerRegistry = handlerRegistry;
        this.timeout = timeout;
    }

    public LocalEventDispatchTask(EventHandlerRegistry handlerRegistry, long timeout, long interval, E event) {
        this.handlerRegistry = handlerRegistry;
        this.timeout = timeout;
        this.interval = interval;
        this.event = event;
    }

    @Override
    public void run() {
        try {
            boolean dispatched = false;

            for (long delay = 0; delay < timeout && !dispatched; delay += interval) {
                EventHandler handler = handlerRegistry.getHandler(event);
                if (handler != null) {
                    handler.handle(event);
                    dispatched = true;
                } else {
                    try {
                        Thread.sleep(interval);
                    } catch (InterruptedException e) {
                        LOGGER.warn("Interrupted while waiting for cluster event handler", e);
                    }
                }
            }
            if (!dispatched) {
                LOGGER.trace("Failed to retrieve handler for cluster event {}", event.getClass());
            }
        } catch (Exception ex) {
            LOGGER.error("Error while dispatching task", ex);
        }
    }

    public long getTimeout() {
        return timeout;
    }

    public void setTimeout(long timeout) {
        this.timeout = timeout;
    }

    public long getInterval() {
        return interval;
    }

    public void setInterval(long interval) {
        this.interval = interval;
    }

}
