package org.emau.icmvc.ganimed.ttp.cm2.internal;

/*-
 * ###license-information-start###
 * gICS - a Generic Informed Consent Service
 * __
 * Copyright (C) 2014 - 2023 Trusted Third Party of the University Medicine Greifswald -
 * 							kontakt-ths@uni-greifswald.de
 *
 * 							concept and implementation
 * 							l.geidel, c.hampf
 * 							web client
 * 							a.blumentritt, m.bialke, f.m.moser
 * 							fhir-api
 * 							m.bialke
 * 							docker
 * 							r. schuldt
 *
 * 							The gICS was developed by the University Medicine Greifswald and published
 * 							in 2014 as part of the research project "MOSAIC" (funded by the DFG HO 1937/2-1).
 *
 * 							Selected functionalities of gICS were developed as
 * 							part of the following research projects:
 * 							- MAGIC (funded by the DFG HO 1937/5-1)
 * 							- MIRACUM (funded by the German Federal Ministry of Education and Research 01ZZ1801M)
 * 							- NUM-CODEX (funded by the German Federal Ministry of Education and Research 01KX2021)
 *
 * 							please cite our publications
 * 							https://doi.org/10.1186/s12911-022-02081-4
 * 							https://doi.org/10.1186/s12967-020-02457-y
 * 							http://dx.doi.org/10.3414/ME14-01-0133
 * 							http://dx.doi.org/10.1186/s12967-015-0545-6
 * 							http://dx.doi.org/10.3205/17gmds146
 * __
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * ###license-information-end###
 */

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.emau.icmvc.ganimed.ttp.cm2.exceptions.UnknownDomainException;
import org.emau.icmvc.ganimed.ttp.cm2.exceptions.VersionConverterClassException;
import org.emau.icmvc.ganimed.ttp.cm2.factories.ReflectionClassFactory;
import org.emau.icmvc.ganimed.ttp.cm2.model.Domain;
import org.emau.icmvc.ganimed.ttp.cm2.version.VersionConverter;

/**
 * cache for version converter
 *
 * @author geidell
 *
 */
public class VersionConverterCache
{
	private static final Logger LOGGER = LogManager.getLogger(VersionConverterCache.class);
	private static volatile boolean INITIALISED = false;
	// domain -> signerId -> signedPolicies
	private static final ReentrantReadWriteLock CACHE_RWL = new ReentrantReadWriteLock();
	// key ist jeweils der domainName
	private static final Map<String, VersionConverter> POLICY_VERSION_CONVERTER_CACHE = new HashMap<>();
	private static final Map<String, VersionConverter> MODULE_VERSION_CONVERTER_CACHE = new HashMap<>();
	private static final Map<String, VersionConverter> CT_VERSION_CONVERTER_CACHE = new HashMap<>();

	private VersionConverterCache()
	{}

	public static boolean isInitialised()
	{
		return INITIALISED;
	}

	public static void init(List<Domain> domains) throws VersionConverterClassException
	{
		CACHE_RWL.writeLock().lock();
		try
		{
			if (INITIALISED)
			{
				return;
			}
			for (Domain domain : domains)
			{
				addDomain(domain);
			}
			if (LOGGER.isDebugEnabled())
			{
				LOGGER.debug("cache filled");
			}
			INITIALISED = true;
		}
		finally
		{
			CACHE_RWL.writeLock().unlock();
		}
	}

	public static void addDomain(Domain domain) throws VersionConverterClassException
	{
		String domainName = domain.getName().intern();
		CACHE_RWL.writeLock().lock();
		try
		{
			if (LOGGER.isDebugEnabled())
			{
				LOGGER.debug("add domain " + domainName);
			}
			VersionConverter policyVersionConverter = initVersionConverter(domain.getPolicyVersionConverter());
			VersionConverter moduleVersionConverter = initVersionConverter(domain.getModuleVersionConverter());
			VersionConverter ctVersionConverter = initVersionConverter(domain.getCTVersionConverter());
			POLICY_VERSION_CONVERTER_CACHE.put(domainName, policyVersionConverter);
			MODULE_VERSION_CONVERTER_CACHE.put(domainName, moduleVersionConverter);
			CT_VERSION_CONVERTER_CACHE.put(domainName, ctVersionConverter);
			if (LOGGER.isDebugEnabled())
			{
				LOGGER.debug("domain " + domainName + " added");
			}
		}
		finally
		{
			CACHE_RWL.writeLock().unlock();
		}
	}

	private static VersionConverter initVersionConverter(String versionConverterClass) throws VersionConverterClassException
	{
		try
		{
			Class<? extends VersionConverter> converterClass = ReflectionClassFactory.getSubClass(versionConverterClass, VersionConverter.class);
			return converterClass.getDeclaredConstructor().newInstance();
		}
		catch (Exception e)
		{
			String message = "exception while instantiating " + versionConverterClass + ": " + e.getMessage();
			LOGGER.error(message);
			throw new VersionConverterClassException(message, e);
		}
	}

	public static void removeDomain(String domainName)
	{
		CACHE_RWL.writeLock().lock();
		try
		{
			POLICY_VERSION_CONVERTER_CACHE.remove(domainName);
			MODULE_VERSION_CONVERTER_CACHE.remove(domainName);
			CT_VERSION_CONVERTER_CACHE.remove(domainName);
		}
		finally
		{
			CACHE_RWL.writeLock().unlock();
		}
	}

	public static VersionConverter getPolicyVersionConverter(String domainName) throws UnknownDomainException
	{
		VersionConverter result;
		CACHE_RWL.readLock().lock();
		try
		{
			result = POLICY_VERSION_CONVERTER_CACHE.get(domainName);
		}
		finally
		{
			CACHE_RWL.readLock().unlock();
		}
		if (result == null)
		{
			String message = "unknown domain: " + domainName;
			LOGGER.error(message);
			throw new UnknownDomainException(message);
		}
		return result;
	}

	public static VersionConverter getModuleVersionConverter(String domainName) throws UnknownDomainException
	{
		VersionConverter result;
		CACHE_RWL.readLock().lock();
		try
		{
			result = MODULE_VERSION_CONVERTER_CACHE.get(domainName);
		}
		finally
		{
			CACHE_RWL.readLock().unlock();
		}
		if (result == null)
		{
			String message = "unknown domain: " + domainName;
			LOGGER.error(message);
			throw new UnknownDomainException(message);
		}
		return result;
	}

	public static VersionConverter getCTVersionConverter(String domainName) throws UnknownDomainException
	{
		VersionConverter result;
		CACHE_RWL.readLock().lock();
		try
		{
			result = CT_VERSION_CONVERTER_CACHE.get(domainName);
		}
		finally
		{
			CACHE_RWL.readLock().unlock();
		}
		if (result == null)
		{
			String message = "unknown domain: " + domainName;
			LOGGER.error(message);
			throw new UnknownDomainException(message);
		}
		return result;
	}
}
