/*-
 *  Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
 * 
 *  This file is part of CityDoctor2.
 *
 *  CityDoctor2 is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  CityDoctor2 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 Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with CityDoctor2.  If not, see <https://www.gnu.org/licenses/>.
 */
package de.hft.stuttgart.citydoctor2.utils;

import java.util.Collection;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class CopyHandler {
	
	
	private Set<Copyable> toBeDoneInstances = new HashSet<>();
	private Map<Copyable, Copyable> finishedInstances = new IdentityHashMap<>();
	
	@SuppressWarnings("unchecked")
	public <T extends Copyable> T copy(T original) {
		toBeDoneInstances.add(original);
		while (!toBeDoneInstances.isEmpty()) {
			handleNextInstance();
		}
		for (Entry<Copyable, Copyable> e : finishedInstances.entrySet()) {
			e.getValue().fillValues(e.getKey(), this);
		}
		return (T) finishedInstances.get(original);
	}
	
	@SuppressWarnings("unchecked")
	public <T extends Copyable> T getCopyInstance(T original) {
		if (original == null) {
			// null gets copied to null
			return null;
		}
		return (T) finishedInstances.get(original);
	}
	
	public void addInstance(Copyable copyable) {
		if (copyable == null) {
			// don't care for null instances
			return;
		}
		if (finishedInstances.containsKey(copyable)) {
			// already processed
			return;
		}
		toBeDoneInstances.add(copyable);
	}
	
	private void handleNextInstance() {
		Iterator<Copyable> iterator = toBeDoneInstances.iterator();
		Copyable next = iterator.next();
		iterator.remove();
		finishedInstances.put(next, next.createCopyInstance());
		next.collectInstances(this);
	}

	public void addInstance(Collection<? extends Copyable> collection) {
		if (collection == null) {
			return;
		}
		for (Copyable c : collection) {
			addInstance(c);
		}
	}


}
