/*-
 * ~~~~~~licensing~~~~~~
 * core-support-runtime
 * ==========
 * 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.support.runtime.hazelcast;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.map.listener.MapListener;

public class HazelcastHelper {
    
    private static final Logger LOG = LoggerFactory.getLogger(HazelcastHelper.class);
    
    public static final String DEFAULT_CACHE_PLATFORM = "platform";
    private HazelcastInstance hazelcastInstance;
    private IMap<String,Object> cache;
    private Map<MapListener, String> listenerIds;
    
    public HazelcastHelper(HazelcastInstance hazelcastInstance) {
        this(hazelcastInstance, DEFAULT_CACHE_PLATFORM);
    }
    
    public HazelcastHelper(HazelcastInstance hazelcastInstance, String cacheName) {
        this(hazelcastInstance, DEFAULT_CACHE_PLATFORM, null, true);
    }
    
    public HazelcastHelper(HazelcastInstance hazelcastInstance, List<MapListener> listeners) {
        this(hazelcastInstance, DEFAULT_CACHE_PLATFORM, listeners, true);
    }
    
    public HazelcastHelper(HazelcastInstance hazelcastInstance, String cacheName, List<MapListener> listeners, boolean activateListeners) {
        super();
        LOG.debug("HazelcastHelper initialization for cache " + cacheName);
        this.hazelcastInstance = hazelcastInstance;
        this.cache = hazelcastInstance.getMap(cacheName);
        listenerIds = new HashMap<>();
        
        if (listeners != null && listeners.size() > 0) {
            if (activateListeners) {
                listeners.stream().forEach(l -> listenerIds.put(l, cache.addEntryListener(l, true)));
            } else {
                listeners.stream().forEach(l -> listenerIds.put(l, null));
            }
        }
    }
    
    public void destroy() {
        LOG.debug("HazelcastHelper destroy actions for cache " + cache.getName());
        if (listenerIds != null && listenerIds.size() > 0) {
            Collection<String> ids = listenerIds.values();
            ids.stream().forEach(id -> cache.removeEntryListener(id));
        }
    }
    
    public Object get(String key) {
        return cache.get(key);
    }
    
    public void put(String key, Object value) {
        cache.put(key, value);
    }
    
    public void put(String key, Object value, long ttl) {
        cache.put(key, value, ttl, TimeUnit.SECONDS);
    }
    
    public void put(String key, Object value, long ttl, TimeUnit timeUnit) {
        cache.put(key, value, ttl, timeUnit);
    }
    
    public void remove(String key) {
        cache.remove(key);
    }
    
    public void activateListeners() {
        if (listenerIds != null && listenerIds.size() > 0) {
            for (MapListener l : listenerIds.keySet()) {
                if (listenerIds.get(l) == null) {
                    listenerIds.put(l, cache.addEntryListener(l, true));
                }
            }
        }
    }
    
    public void addListener(MapListener listener) {
        listenerIds.put(listener, cache.addEntryListener(listener, true));
    }
    
    public void removeListener(MapListener listener) {
        if (listenerIds.containsKey(listener)) {
            cache.removeEntryListener(listenerIds.get(listener));
        } else {
            throw new IllegalArgumentException("Listener not registered");
        }
    }

    public HazelcastInstance getHazelcastInstance() {
        return hazelcastInstance;
    }

    public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
        this.hazelcastInstance = hazelcastInstance;
    }
    
}
