/*
 * Copyright 2018 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.request;

import java.util.Collection;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;

import org.eclipse.emf.cdo.CDOObject;

import com.b2international.snowowl.core.domain.TransactionContext;
import com.b2international.snowowl.core.events.DelegatingRequest;
import com.b2international.snowowl.core.events.Request;
import com.b2international.snowowl.core.events.bulk.BulkRequest;
import com.b2international.snowowl.core.exceptions.ComponentNotFoundException;
import com.b2international.snowowl.snomed.Concept;
import com.b2international.snowowl.snomed.Description;
import com.b2international.snowowl.snomed.Relationship;
import com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants;
import com.b2international.snowowl.snomed.datastore.id.SnomedIdentifiers;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;

/**
 * @since 6.5
 * @param <C>
 * @param <T>
 * @param <R>
 */
public final class SnomedBulkRequest<R> extends DelegatingRequest<TransactionContext, TransactionContext, R> {

	SnomedBulkRequest(Request<TransactionContext, R> next) {
		super(next);
	}

	@Override
	public R execute(TransactionContext context) {
		ImmutableList.Builder<SnomedComponentRequest<?>> requests = ImmutableList.builder();
		collectNestedRequests(next(), requests);
		
		// Prefetch all component IDs mentioned in reference set member creation requests, abort if any of them can not be found
		final Set<String> requiredComponentIds = requests.build()
			.stream()
			.flatMap(request -> request.getRequiredComponentIds(context).stream())
			.filter(componentId -> SnomedTerminologyComponentConstants.getTerminologyComponentIdValueSafe(componentId) != -1L) // just in case filter out invalid component IDs
			.collect(Collectors.toSet());
		
		final Multimap<Class<? extends CDOObject>, String> componentIdsByType = FluentIterable.from(requiredComponentIds)
				.index(componentId -> {
					switch (SnomedIdentifiers.getComponentCategory(componentId)) {
					case CONCEPT: return Concept.class;
					case DESCRIPTION: return Description.class;
					case RELATIONSHIP: return Relationship.class;
					default: throw new UnsupportedOperationException("Cannot determine CDO class from component ID '" + componentId + "'.");
					}
				});
		
		try {
			for (final Entry<Class<? extends CDOObject>, Collection<String>> idsForType : componentIdsByType.asMap().entrySet()) {
				context.lookup(idsForType.getValue(), idsForType.getKey());	
			}
		} catch (final ComponentNotFoundException e) {
			throw e.toBadRequestException();
		}
		
		// bind additional caches to the context
		TransactionContext newContext = context.inject()
			.bind(Synonyms.class, new Synonyms(context))
			.build();
		
		return next(newContext);
	}

	private static void collectNestedRequests(Request<?, ?> root, ImmutableList.Builder<SnomedComponentRequest<?>> requests) {
		if (root instanceof SnomedComponentRequest<?>) {
			requests.add((SnomedComponentRequest<?>) root);
		} else if (root instanceof DelegatingRequest<?, ?, ?>) {
			collectNestedRequests(((DelegatingRequest<?, ?, ?>) root).next(), requests);
		} else if (root instanceof BulkRequest<?>) {
			((BulkRequest<?>) root).getRequests().forEach(req -> {
				collectNestedRequests(req, requests);
			});
		}
	}
	
}

@@ -799,47 +799,8 @@
 s;%0A%0A
-import org.eclipse.emf.cdo.CDOObject;%0A%0A
 impo
@@ -1170,23 +1170,58 @@
 .snomed.
-Concept
+common.SnomedTerminologyComponentConstants
 ;%0Aimport
@@ -1256,27 +1256,46 @@
 .snomed.
-Description
+datastore.id.SnomedIdentifiers
 ;%0Aimport
@@ -1330,28 +1330,59 @@
 .snomed.
-Relationship
+datastore.index.entry.SnomedConceptDocument
 ;%0Aimport
@@ -1421,50 +1421,137 @@
 med.
-common.SnomedTerminologyComponentConstants
+datastore.index.entry.SnomedDescriptionIndexEntry;%0Aimport com.b2international.snowowl.snomed.datastore.index.entry.SnomedDocument
 ;%0Aim
@@ -1601,35 +1601,55 @@
 astore.i
-d.SnomedIdentifiers
+ndex.entry.SnomedRelationshipIndexEntry
 ;%0Aimport
@@ -2730,32 +2730,37 @@
 s%3C? extends 
-CDOObjec
+SnomedDocumen
 t%3E, String%3E 
@@ -2944,23 +2944,37 @@
  return 
+Snomed
 Concept
+Document
 .class;%0A
@@ -3003,16 +3003,22 @@
  return 
+Snomed
 Descript
@@ -3020,16 +3020,26 @@
 cription
+IndexEntry
 .class;%0A
@@ -3069,16 +3069,22 @@
  return 
+Snomed
 Relation
@@ -3087,16 +3087,26 @@
 tionship
+IndexEntry
 .class;%0A
@@ -3260,16 +3260,17 @@
 ry %7B%0A%09%09%09
+%09
 for (fin
@@ -3298,16 +3298,21 @@
 nds 
-CDOObjec
+SnomedDocumen
 t%3E, 

fix SnomedBulkRequest