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

import static org.apache.ignite.IgniteSystemProperties.IGNITE_QUIET;

import java.io.File;

import org.apache.camel.util.ObjectHelper;
import org.apache.ignite.Ignite;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.CacheRebalanceMode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.configuration.TransactionConfiguration;
import org.apache.ignite.logger.jcl.JclLogger;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IgniteInstanceIgniter {
    
    private static final Logger LOG = LoggerFactory.getLogger(IgniteInstanceIgniter.class);
    
    private BundleContext bundleContext;
    private String workDirectory;
    private long metricsLogFrequency;
    
    private String platformCacheName;
    private String commonCacheName;
    private String rebalanceMode;
    private String cacheMode;
    private String atomicityMode;
    private int backups;
    
    private Ignite ignite;
    
    public IgniteInstanceIgniter() {}
    
    public void start() throws Exception {
    	ObjectHelper.notNull(bundleContext, "bundleContext");
        ObjectHelper.notNull(workDirectory, "workDirectory");

        IgniteConfiguration cfg = createConfig();
        LOG.info("IgniteConfiguration created for workDirectory {}", workDirectory);
        
        CacheConfiguration<String, Object> platformCacheCfg = createCacheConfig(platformCacheName);
        CacheConfiguration<String, Object> commonCacheCfg = createCacheConfig(commonCacheName);
        cfg.setCacheConfiguration(platformCacheCfg, commonCacheCfg);
        LOG.info("Common CacheConfiguration inited for cacheName {}", platformCacheName);
        LOG.info("Common CacheConfiguration inited for cacheName {}", commonCacheName);
        
        System.setProperty(IGNITE_QUIET, "false");
        
        ignite = Ignition.getOrStart(cfg);
        ignite.cluster().active(true);
        
        ignite.getOrCreateCache(platformCacheCfg);
        ignite.getOrCreateCache(commonCacheCfg);
        
        ignite.cluster().baselineAutoAdjustEnabled(true);
        //default timeout 300s
//        ignite.cluster().baselineAutoAdjustTimeout(30000);
        LOG.info("Ignite instance initialized");
        
        bundleContext.registerService(Ignite.class, ignite, null);
        LOG.info("Ignite service published");
    }
    
    public void stop() throws Exception {
        if (ignite != null) {
            ignite.close();
        }
    }
    
    protected CacheConfiguration<String, Object> createCacheConfig(String cacheName) {
        CacheConfiguration<String, Object> cacheCfg = new CacheConfiguration<>();
        cacheCfg.setName(cacheName);
        cacheCfg.setRebalanceMode(CacheRebalanceMode.valueOf(rebalanceMode));
        cacheCfg.setCacheMode(CacheMode.valueOf(cacheMode));
        cacheCfg.setAtomicityMode(CacheAtomicityMode.valueOf(atomicityMode));
        cacheCfg.setBackups(backups);
        return cacheCfg;
    }

    protected IgniteConfiguration createConfig() {
        IgniteConfiguration cfg = new IgniteConfiguration();
//        cfg.setConsistentId();

        TcpDiscoverySpi spi = new TcpDiscoverySpi();
//        spi.setIpFinder(new TcpDiscoverySharedFsIpFinder() {{setPath(workDirectory + "/addresses");}});
        spi.setIpFinder(new TcpDiscoveryMulticastIpFinder());
        cfg.setDiscoverySpi(spi);
                
        cfg.setGridLogger(new JclLogger());
        cfg.setTransactionConfiguration(new TransactionConfiguration());
        
        //Persistence
        DataStorageConfiguration storageCfg = new DataStorageConfiguration();
        storageCfg.getDefaultDataRegionConfiguration().setPersistenceEnabled(true);
        cfg.setWorkDirectory(workDirectory);
        cfg.setIgniteHome(workDirectory);
        cfg.setDataStorageConfiguration(storageCfg);
        
        cfg.setMetricsLogFrequency(metricsLogFrequency);
        
        return cfg;
    }

	public BundleContext getBundleContext() {
		return bundleContext;
	}

	public void setBundleContext(BundleContext bundleContext) {
		this.bundleContext = bundleContext;
	}

	public String getWorkDirectory() {
		return workDirectory;
	}

	public void setWorkDirectory(String workDirectory) {
		if (workDirectory != null && 
				!workDirectory.startsWith(File.separator) && !workDirectory.contains(":")) {
			workDirectory = System.getProperty("karaf.home", "/opt/karaf") + File.separator + workDirectory;
		}
		this.workDirectory = workDirectory;
	}

	public long getMetricsLogFrequency() {
        return metricsLogFrequency;
    }

    public void setMetricsLogFrequency(long metricsLogFrequency) {
        this.metricsLogFrequency = metricsLogFrequency;
    }

    public String getPlatformCacheName() {
        return platformCacheName;
    }

    public void setPlatformCacheName(String platformCacheName) {
        this.platformCacheName = platformCacheName;
    }

    public String getCommonCacheName() {
        return commonCacheName;
    }

    public void setCommonCacheName(String commonCacheName) {
        this.commonCacheName = commonCacheName;
    }

    public String getRebalanceMode() {
		return rebalanceMode;
	}

	public void setRebalanceMode(String rebalanceMode) {
		this.rebalanceMode = rebalanceMode;
	}

	public String getCacheMode() {
		return cacheMode;
	}

	public void setCacheMode(String cacheMode) {
		this.cacheMode = cacheMode;
	}

	public String getAtomicityMode() {
		return atomicityMode;
	}

	public void setAtomicityMode(String atomicityMode) {
		this.atomicityMode = atomicityMode;
	}

	public int getBackups() {
		return backups;
	}

	public void setBackups(int backups) {
		this.backups = backups;
	}

}
