/*
 * Copyright 2011-2019 B2i Healthcare Pte Ltd, http://b2i.sg
 * 
 * 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 com.b2international.snowowl.snomed.datastore.id;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Set;
import java.util.stream.Collectors;

import org.eclipse.core.runtime.IProgressMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.b2international.index.Index;
import com.b2international.index.Indexes;
import com.b2international.index.mapping.Mappings;
import com.b2international.snowowl.core.config.SnowOwlConfiguration;
import com.b2international.snowowl.core.setup.DefaultBootstrapFragment;
import com.b2international.snowowl.core.setup.Environment;
import com.b2international.snowowl.datastore.config.IndexSettings;
import com.b2international.snowowl.eventbus.IEventBus;
import com.b2international.snowowl.snomed.datastore.config.SnomedCoreConfiguration;
import com.b2international.snowowl.snomed.datastore.config.SnomedIdentifierConfiguration;
import com.b2international.snowowl.snomed.datastore.config.SnomedIdentifierConfiguration.IdGenerationStrategy;
import com.b2international.snowowl.snomed.datastore.id.cis.CisSnomedIdentifierService;
import com.b2international.snowowl.snomed.datastore.id.domain.SctId;
import com.b2international.snowowl.snomed.datastore.id.gen.ItemIdGenerationStrategy;
import com.b2international.snowowl.snomed.datastore.id.gen.SequentialItemIdGenerationStrategy;
import com.b2international.snowowl.snomed.datastore.id.memory.DefaultSnomedIdentifierService;
import com.b2international.snowowl.snomed.datastore.id.reservations.ISnomedIdentifierReservationService;
import com.b2international.snowowl.snomed.datastore.internal.id.reservations.IdSetReservation;
import com.b2international.snowowl.snomed.datastore.internal.id.reservations.SnomedIdentifierReservationServiceImpl;
import com.b2international.snowowl.snomed.datastore.internal.id.reservations.UniqueInStoreReservation;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;

/**
 * @since 4.5
 */
public class SnomedIdentifierBootstrap extends DefaultBootstrapFragment {

	private static final Logger LOGGER = LoggerFactory.getLogger(SnomedIdentifierBootstrap.class);
	private static final String SNOMED_IDS_INDEX = "snomedids";
	private static final String STORE_RESERVATIONS = "store_reservations";

	@Override
	public void init(final SnowOwlConfiguration configuration, final Environment env) throws Exception {
		checkIdGenerationSource(configuration);

		final ISnomedIdentifierReservationService reservationService = new SnomedIdentifierReservationServiceImpl();
		env.services().registerService(ISnomedIdentifierReservationService.class, reservationService);

		registerDefaultReservations(env, reservationService);
	}

	@Override
	public void run(SnowOwlConfiguration configuration, Environment env, IProgressMonitor monitor) throws Exception {
		if (env.isServer() || env.isEmbedded()) {
			final ISnomedIdentifierReservationService reservationService = env.service(ISnomedIdentifierReservationService.class);
			final SnomedIdentifierConfiguration conf = configuration.getModuleConfig(SnomedCoreConfiguration.class).getIds();
			registerSnomedIdentifierService(conf, env, reservationService);
		}
	}

	private void registerDefaultReservations(final Environment env, final ISnomedIdentifierReservationService reservationService) {
		final UniqueInStoreReservation storeReservation = new UniqueInStoreReservation(env.provider(IEventBus.class));
		reservationService.create(STORE_RESERVATIONS, storeReservation);
		
		final File reservationsDirectory = env.getConfigDirectory().toPath().resolve("reservations").toFile();
		if (reservationsDirectory.exists() && reservationsDirectory.isDirectory()) {
			for (File reservationFile : reservationsDirectory.listFiles()) {
				final String reservationFileName = reservationFile.getName();
				if (reservationFileName.endsWith(".txt")) {
					try {
						final Set<String> idsToExclude = Files.lines(reservationFile.toPath(), Charsets.UTF_8)
								.filter(SnomedIdentifiers::isValid)
								.collect(Collectors.toSet());
						
						if (idsToExclude.isEmpty()) {
							LOGGER.warn(String.format("Could not find any valid Snomed Identifier in the source file: '%s'", reservationFileName));
						} else {
							reservationService.create(com.google.common.io.Files.getNameWithoutExtension(reservationFileName), new IdSetReservation(idsToExclude));
						}
					} catch (IOException e) {
						LOGGER.error(String.format("Could not read file: '%s'", reservationFileName));
					}
				}
			}
		}
		
	}

	private void checkIdGenerationSource(final SnowOwlConfiguration configuration) {
		final SnomedIdentifierConfiguration conf = configuration.getModuleConfig(SnomedIdentifierConfiguration.class);
		final IdGenerationStrategy idGenerationSource = conf.getStrategy();

		if (null == idGenerationSource) {
			throw new IllegalStateException("ID generation source is not configured.");
		}
	}

	private void registerSnomedIdentifierService(final SnomedIdentifierConfiguration conf, final Environment env, final ISnomedIdentifierReservationService reservationService) {
		ISnomedIdentifierService identifierService = null;

		switch (conf.getStrategy()) {
		case EMBEDDED:
			final Index index = Indexes.createIndex(SNOMED_IDS_INDEX, env.service(ObjectMapper.class), new Mappings(SctId.class), env.service(IndexSettings.class));
			index.admin().create();
			final ItemIdGenerationStrategy generationStrategy = new SequentialItemIdGenerationStrategy(reservationService); 
			identifierService = new DefaultSnomedIdentifierService(index, generationStrategy, reservationService, conf);
			break;
		case CIS:
			final ObjectMapper mapper = new ObjectMapper();
			identifierService = new CisSnomedIdentifierService(conf, reservationService, mapper);
			break;
		default:
			throw new IllegalStateException(String.format("Unknown ID generation source configured: %s. ", conf.getStrategy()));
		}

		env.services().registerService(ISnomedIdentifierService.class, identifierService);
		LOGGER.info("Snow Owl is configured to use {} based identifier service.", conf.getStrategy());
	}

}


@@ -4768,30 +4768,16 @@
 ER.warn(
-String.format(
 %22Could n
@@ -4825,34 +4825,34 @@
 e source file: '
-%25s
+%7B%7D
 '%22, reservationF
@@ -4855,25 +4855,24 @@
 ionFileName)
-)
 ;%0A%09%09%09%09%09%09%7D el
@@ -5077,30 +5077,16 @@
 R.error(
-String.format(
 %22Could n
@@ -5100,18 +5100,18 @@
  file: '
-%25s
+%7B%7D
 '%22, rese
@@ -5126,17 +5126,16 @@
 ileName)
-)
 ;%0A%09%09%09%09%09%7D

Remove String.format calls from SnomedIdentifierBootstrap