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

import java.util.ArrayList;
import java.util.List;

import org.citygml4j.core.model.bridge.AbstractBridge;
import org.citygml4j.core.model.bridge.BridgeInstallation;
import org.citygml4j.core.model.bridge.BridgeInstallationProperty;
import org.citygml4j.core.model.core.AbstractSpaceBoundaryProperty;
import org.citygml4j.core.util.geometry.GeometryFactory;
import org.xmlobjects.gml.model.geometry.aggregates.MultiSurface;
import org.xmlobjects.gml.model.geometry.aggregates.MultiSurfaceProperty;
import org.xmlobjects.gml.model.geometry.primitives.Solid;
import org.xmlobjects.gml.model.geometry.primitives.SolidProperty;

import de.hft.stuttgart.citydoctor2.check.Check;
import de.hft.stuttgart.citydoctor2.check.CheckError;
import de.hft.stuttgart.citydoctor2.check.CheckId;
import de.hft.stuttgart.citydoctor2.parser.ParserConfiguration;
import de.hft.stuttgart.citydoctor2.utils.CityGmlUtils;
import de.hft.stuttgart.citydoctor2.utils.CopyHandler;
import de.hft.stuttgart.citydoctor2.utils.Copyable;

/**
 * Bridge representation object of CityGML bridge objects
 * 
 * @author Matthias Betz
 *
 */
public class BridgeObject extends CityObject {

	private static final long serialVersionUID = 6301112640328373842L;

	public enum BridgeType {
		BRIDGE, BRIDGE_PART
	}

	private AbstractBridge ab;
	private BridgeType type;
	
	private List<BridgeObject> parts = null;
	
	private List<BridgeConstructiveElement> elements = null;
	private List<BoundarySurface> boundarySurfaces = new ArrayList<>(2);
	private List<Installation> bridgeInstallations = new ArrayList<>(2);
	
	public BridgeObject(BridgeType type, AbstractBridge ab) {
		this.ab = ab;
		this.type = type;
	}

	@Override
	public FeatureType getFeatureType() {
		return FeatureType.BRIDGE;
	}
	
	public List<BridgeConstructiveElement> getConstructiveElements() {
		if (elements == null) {
			elements = new ArrayList<>(2);
		}
		return elements;
	}
	
	public List<Installation> getBridgeInstallations() {
		return bridgeInstallations;
	}

	@Override
	public void reCreateGeometries(GeometryFactory factory, ParserConfiguration config) {
		for (Geometry geom : getGeometries()) {
			if (geom.getType() == GeometryType.MULTI_SURFACE) {
				MultiSurface ms = CityGmlUtils.createMultiSurface(geom, factory, config);
				setMultiSurfaceAccordingToLod(geom, ms);
			} else {
				Solid solid = CityGmlUtils.createSolid(geom, factory, config);
				setSolidAccordingToLod(geom, solid);
			}
		}
		for (BoundarySurface bs : boundarySurfaces) {
			bs.reCreateGeometries(factory, config);
		}
		for (Installation bi : bridgeInstallations) {
			bi.reCreateGeometries(factory, config);
		}
		if (parts != null) {
			for (BridgeObject part : parts) {
				part.reCreateGeometries(factory, config);
			}
		}
		if (elements != null) {
			for (BridgeConstructiveElement ele : elements) {
				ele.reCreateGeometries(factory, config);
			}
		}
	}

	private void setMultiSurfaceAccordingToLod(Geometry geom, MultiSurface ms) {
		switch (geom.getLod()) {
		case LOD1:
			ab.getDeprecatedProperties().setLod1MultiSurface(new MultiSurfaceProperty(ms));
			break;
		case LOD2:
			ab.setLod2MultiSurface(new MultiSurfaceProperty(ms));
			break;
		case LOD3:
			ab.setLod3MultiSurface(new MultiSurfaceProperty(ms));
			break;
		case LOD4:
			ab.getDeprecatedProperties().setLod4MultiSurface(new MultiSurfaceProperty(ms));
			break;
		default:
			throw new IllegalStateException("Cannot add " + geom.getLod() + " multi surface to bridges");
		}
	}

	private void setSolidAccordingToLod(Geometry geom, Solid solid) {
		switch (geom.getLod()) {
		case LOD1:
			ab.setLod1Solid(new SolidProperty(solid));
			break;
		case LOD2:
			ab.setLod2Solid(new SolidProperty(solid));
			break;
		case LOD3:
			ab.setLod3Solid(new SolidProperty(solid));
			break;
		case LOD4:
			ab.getDeprecatedProperties().setLod4Solid(new SolidProperty(solid));
			break;
		default:
			throw new IllegalStateException("Cannot add " + geom.getLod() + " solid to bridges");
		}
	}
	
	public void addBridgeInstallation(Installation coBi) {
		bridgeInstallations.add(coBi);
		coBi.setParent(this);
	}

	@Override
	public void clearAllContainedCheckResults() {
		super.clearAllContainedCheckResults();
		for (BoundarySurface bs : boundarySurfaces) {
			bs.clearAllContainedCheckResults();
		}
		for (Installation bi : bridgeInstallations) {
			bi.clearAllContainedCheckResults();
		}
		if (parts != null) {
			for (BridgeObject part : parts) {
				part.clearAllContainedCheckResults();
			}
		}
		if (elements != null) {
			for (BridgeConstructiveElement ele : elements) {
				ele.clearAllContainedCheckResults();
			}
		}
	}

	@Override
	public void collectContainedErrors(List<CheckError> errors) {
		super.collectContainedErrors(errors);
		for (BoundarySurface bs : boundarySurfaces) {
			bs.collectContainedErrors(errors);
		}
		for (Installation bi : bridgeInstallations) {
			bi.collectContainedErrors(errors);
		}
		if (parts != null) {
			for (BridgeObject part : parts) {
				part.collectContainedErrors(errors);
			}
		}
		if (elements != null) {
			for (BridgeConstructiveElement ele : elements) {
				ele.collectContainedErrors(errors);
			}
		}
	}

	@Override
	public boolean containsAnyError() {
		boolean hasError = super.containsAnyError();
		if (hasError) {
			return true;
		}
		for (Installation bi : bridgeInstallations) {
			if (bi.containsAnyError()) {
				return true;
			}
		}
		for (BoundarySurface bs : boundarySurfaces) {
			if (bs.containsAnyError()) {
				return true;
			}
		}
		if (doPartsContainAnyError()) {
			return true;
		}
		if (elements != null) {
			for (BridgeConstructiveElement ele : elements) {
				if (ele.containsAnyError()) {
					return true;
				}
			}
		}
		return false;
	}

	private boolean doPartsContainAnyError() {
		if (parts != null) {
			for (BridgeObject part : parts) {
				if (part.containsAnyError()) {
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public boolean containsError(CheckId checkIdentifier) {
		boolean hasError = super.containsError(checkIdentifier);
		if (hasError) {
			return true;
		}
		for (Installation bi : bridgeInstallations) {
			if (bi.containsError(checkIdentifier)) {
				return true;
			}
		}
		for (BoundarySurface bs : boundarySurfaces) {
			if (bs.containsError(checkIdentifier)) {
				return true;
			}
		}
		if (doPartsContainError(checkIdentifier)) {
			return true;
		}
		if (elements != null) {
			for (BridgeConstructiveElement ele : elements) {
				if (ele.containsError(checkIdentifier)) {
					return true;
				}
			}
		}
		return false;
	}

	private boolean doPartsContainError(CheckId checkIdentifier) {
		if (parts != null) {
			for (BridgeObject part : parts) {
				if (part.containsError(checkIdentifier)) {
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public void accept(Check c) {
		super.accept(c);
		if (c.canExecute(this)) {
			c.check(this);
		}
		for (BoundarySurface bs : boundarySurfaces) {
			bs.accept(c);
		}
		for (Installation bi : bridgeInstallations) {
			bi.accept(c);
		}
		if (parts != null) {
			for (BridgeObject part : parts) {
				part.accept(c);
			}
		}
		if (elements != null) {
			for (BridgeConstructiveElement ele : elements) {
				ele.accept(c);
			}
		}
	}

	/**
	 * Getter method for type
	 * 
	 * @return the type
	 */
	public BridgeType getType() {
		return type;
	}

	/**
	 * Setter Method for type
	 * 
	 * @param type the type to set
	 */
	public void setType(BridgeType type) {
		this.type = type;
	}

	public void addBoundarySurface(BoundarySurface bs) {
		boundarySurfaces.add(bs);
		bs.setParent(this);
	}

	@Override
	public AbstractBridge getGmlObject() {
		return ab;
	}

	@Override
	public void unsetGmlGeometries() {
		ab.setLod1Solid(null);
		ab.setLod2Solid(null);
		ab.setLod3Solid(null);
		ab.setLod2MultiSurface(null);
		ab.setLod3MultiSurface(null);
		ab.getDeprecatedProperties().setLod1MultiSurface(null);
		ab.getDeprecatedProperties().setLod4MultiSurface(null);
		ab.getDeprecatedProperties().setLod4Solid(null);
		for (BoundarySurface bs : boundarySurfaces) {
			bs.unsetGmlGeometries();
		}
		for (Installation bi : bridgeInstallations) {
			bi.unsetGmlGeometries();
		}
		if (parts != null) {
			for (BridgeObject part : parts) {
				part.unsetGmlGeometries();
			}
		}
		if (elements != null) {
			for (BridgeConstructiveElement ele : elements) {
				ele.unsetGmlGeometries();
			}
		}
	}

	public void setGmlObject(AbstractBridge aBridge) {
		ab = aBridge;
	}

	@Override
	public String toString() {
		return "BridgeObject [type=" + type + ", id=" + getGmlId() + "]";
	}

	@Override
	public void prepareForChecking() {
		super.prepareForChecking();
		if (elements != null) {
			for (BridgeConstructiveElement e : elements) {
				e.prepareForChecking();
			}
		}
		if (parts != null) {
			for (BridgeObject part : parts) {
				part.prepareForChecking();
			}
		}
		for (BoundarySurface bs : boundarySurfaces) {
			bs.prepareForChecking();
		}
		for (Installation bi : bridgeInstallations) {
			bi.prepareForChecking();
		}
	}

	@Override
	public void clearMetaInformation() {
		super.clearMetaInformation();
		for (BoundarySurface bs : boundarySurfaces) {
			bs.clearMetaInformation();
		}
		for (Installation bi : bridgeInstallations) {
			bi.clearMetaInformation();
		}
		if (parts != null) {
			for (BridgeObject part : parts) {
				part.clearMetaInformation();
			}
		}
		if (elements != null) {
			for (BridgeConstructiveElement ele : elements) {
				ele.clearMetaInformation();
			}
		}
	}
	
	@Override
	public void collectInstances(CopyHandler handler) {
		super.collectInstances(handler);
		for (BoundarySurface bs : boundarySurfaces) {
			handler.addInstance(bs);
		}
		for (Installation bi : bridgeInstallations) {
			handler.addInstance(bi);
		}
		if (parts != null) {
			for (BridgeObject part : parts) {
				handler.addInstance(part);
			}
		}
		if (elements != null) {
			for (BridgeConstructiveElement ele : elements) {
				handler.addInstance(ele);
			}
		}
	}
	
	public void anonymize() {
		for (Geometry geom : getGeometries()) {
			geom.anonymize();
		}
		org.citygml4j.core.model.bridge.Bridge gmlB = new org.citygml4j.core.model.bridge.Bridge();
		gmlB.setId(GmlId.generateId().getGmlString());
		for (Installation bi : getBridgeInstallations()) {
			bi.anonymize();
			gmlB.getBridgeInstallations().add(new BridgeInstallationProperty((BridgeInstallation) bi.getGmlObject()));
		}
		for (BoundarySurface bs : getBoundarySurfaces()) {
			bs.anonymize();
			gmlB.addBoundary(new AbstractSpaceBoundaryProperty(bs.getGmlObject()));
		}
		this.ab = gmlB;
	}
	
	
	@Override
	public void fillValues(Copyable original, CopyHandler handler) {
		super.fillValues(original, handler);
		BridgeObject originalBo = (BridgeObject) original;
		for (BoundarySurface originalBs : originalBo.boundarySurfaces) {
			boundarySurfaces.add(handler.getCopyInstance(originalBs));
		}
		for (Installation originalBi : originalBo.bridgeInstallations) {
			bridgeInstallations.add(handler.getCopyInstance(originalBi));
		}
		if (originalBo.parts != null) {
			for (BridgeObject part : originalBo.parts) {
				getParts().add(handler.getCopyInstance(part));
			}
		}
		if (originalBo.elements != null) {
			for (BridgeConstructiveElement ele : originalBo.elements) {
				getConstructiveElements().add(handler.getCopyInstance(ele));
			}
		}
	}
	
	public List<BoundarySurface> getBoundarySurfaces() {
		return boundarySurfaces;
	}
	
	public void addConstructiveElement(BridgeConstructiveElement element) {
		getConstructiveElements().add(element);
	}

	@Override
	public Copyable createCopyInstance() {
		return new BridgeObject(type, ab);
	}
	
	public List<BridgeObject> getParts() {
		if (parts == null) {
			parts  = new ArrayList<>(2);
		}
		return parts;
	}

	public void addBridgePart(BridgeObject bPart) {
		getParts().add(bPart);
	}
	
}
