/*-
 *  Copyright 2022 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.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.citygml4j.core.model.core.AbstractSpaceBoundaryProperty;
import org.citygml4j.core.model.deprecated.bridge.DeprecatedPropertiesOfBridgeConstructiveElement;
import org.citygml4j.core.util.geometry.GeometryFactory;
import org.xmlobjects.gml.model.geometry.GeometryProperty;
import org.xmlobjects.gml.model.geometry.aggregates.MultiSurface;
import org.xmlobjects.gml.model.geometry.aggregates.MultiSurfaceProperty;
import org.xmlobjects.gml.model.geometry.complexes.CompositeSurface;
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;

public class BridgeConstructiveElement extends CityObject {
	
	private static final Logger logger = LogManager.getLogger(BridgeConstructiveElement.class);

	private static final String CANNOT_ADD = "Cannot add ";

	private static final long serialVersionUID = 7353233899458901155L;

	private org.citygml4j.core.model.bridge.BridgeConstructiveElement gmlBridgeElement;
	private List<BoundarySurface> boundarySurfaceList = new ArrayList<>();


	public BridgeConstructiveElement(org.citygml4j.core.model.bridge.BridgeConstructiveElement gmlObject) {
		this.gmlBridgeElement = gmlObject;
	}

	@Override
	public Copyable createCopyInstance() {
		return new BridgeConstructiveElement(gmlBridgeElement);
	}

	@Override
	public void reCreateGeometries(GeometryFactory factory, ParserConfiguration config) {
		// only handles CityGML2 for now
		// unknown which CityGML is handled here
		// need context information to decide
		for (Geometry geom : getGeometries()) {
			switch (geom.getType()) {
			case SOLID:
				Solid solid = CityGmlUtils.createSolid(geom, factory, config);
				setSolidAccordingToLod(geom, solid);
				break;
			case MULTI_SURFACE:
				MultiSurface ms = CityGmlUtils.createMultiSurface(geom, factory, config);
				setMultiSurfaceAccordingToLod(geom, ms);
				break;
			case COMPOSITE_SURFACE:
				CompositeSurface cs = CityGmlUtils.createCompositeSurface(geom, factory, config);
				setCompositeSurfaceAccordingToLod(geom, cs);
				break;
			}
		}
		for (BoundarySurface bs : boundarySurfaceList) {
			reCreateBoundarySurface(factory, config, bs);
		}
	}
	
	@Override
	public void accept(Check c) {
		super.accept(c);
		if (c.canExecute(this)) {
			c.check(this);
		}
		for (BoundarySurface bs : boundarySurfaceList) {
			bs.accept(c);
		}
	}
	
	@Override
	public void collectContainedErrors(List<CheckError> errors) {
		super.collectContainedErrors(errors);
		for (BoundarySurface bs : boundarySurfaceList) {
			bs.collectContainedErrors(errors);
		}
	}
	
	@Override
	public void clearAllContainedCheckResults() {
		super.clearAllContainedCheckResults();
		for (BoundarySurface bs : boundarySurfaceList) {
			bs.clearAllContainedCheckResults();
		}
	}
	
	@Override
	public boolean containsError(CheckId checkIdentifier) {
		boolean hasError = super.containsError(checkIdentifier);
		if (hasError) {
			return true;
		}
		for (BoundarySurface bs : boundarySurfaceList) {
			if (bs.containsError(checkIdentifier)) {
				return true;
			}
		}
		return false;
	}
	
	@Override
	public boolean containsAnyError() {
		boolean hasError = super.containsAnyError();
		if (hasError) {
			return true;
		}
		for (BoundarySurface bs : boundarySurfaceList) {
			if (bs.containsAnyError()) {
				return true;
			}
		}
		return false;
	}
	
	private void reCreateBoundarySurface(GeometryFactory factory, ParserConfiguration config, BoundarySurface bs) {
		if (bs.getGeometries().isEmpty()) {
			for (AbstractSpaceBoundaryProperty bsp : gmlBridgeElement.getBoundaries()) {
				if (bsp.getObject() != null && bsp.getObject() == bs.getGmlObject()) {
					logger.warn("Found empty boundary surface: {}, removing from BridgeConstructiveElement", bs.getGmlId());
					gmlBridgeElement.getBoundaries().remove(bsp);
					break;
				}
			}
			return;
		}
		bs.reCreateGeometries(factory, config);
	}

	private void setCompositeSurfaceAccordingToLod(Geometry geom, CompositeSurface cs) {
		switch (geom.getLod()) {
		case LOD1:
			gmlBridgeElement.getDeprecatedProperties().setLod1Geometry(new GeometryProperty<>(cs));
			break;
		case LOD2:
			gmlBridgeElement.getDeprecatedProperties().setLod2Geometry(new GeometryProperty<>(cs));
			break;
		case LOD3:
			gmlBridgeElement.getDeprecatedProperties().setLod3Geometry(new GeometryProperty<>(cs));
			break;
		case LOD4:
			gmlBridgeElement.getDeprecatedProperties().setLod4Geometry(new GeometryProperty<>(cs));
			break;
		default:
			throw new IllegalStateException(CANNOT_ADD + geom.getLod() + " composite surface to buildings");
		}		
	}

	private void setSolidAccordingToLod(Geometry geom, Solid solid) {
		switch (geom.getLod()) {
		case LOD1:
			gmlBridgeElement.getDeprecatedProperties().setLod1Geometry(new SolidProperty(solid));
			break;
		case LOD2:
			gmlBridgeElement.getDeprecatedProperties().setLod2Geometry(new SolidProperty(solid));
			break;
		case LOD3:
			gmlBridgeElement.getDeprecatedProperties().setLod3Geometry(new SolidProperty(solid));
			break;
		case LOD4:
			gmlBridgeElement.getDeprecatedProperties().setLod4Geometry(new SolidProperty(solid));
			break;
		default:
			throw new IllegalStateException(CANNOT_ADD + geom.getLod() + " solid to buildings");
		}
	}
	
	private void setMultiSurfaceAccordingToLod(Geometry geom, MultiSurface ms) {
		switch (geom.getLod()) {
		case LOD0:
			gmlBridgeElement.getDeprecatedProperties().setLod1Geometry(new MultiSurfaceProperty(ms));
			break;
		case LOD1:
			gmlBridgeElement.getDeprecatedProperties().setLod1Geometry(new MultiSurfaceProperty(ms));
			break;
		case LOD2:
			gmlBridgeElement.getDeprecatedProperties().setLod1Geometry(new MultiSurfaceProperty(ms));
			break;
		case LOD3:
			gmlBridgeElement.getDeprecatedProperties().setLod1Geometry(new MultiSurfaceProperty(ms));
			break;
		case LOD4:
			gmlBridgeElement.getDeprecatedProperties().setLod1Geometry(new MultiSurfaceProperty(ms));
			break;
		default:
			throw new IllegalStateException(CANNOT_ADD + geom.getLod() + " multi surface to buildings");
		}
	}

	@Override
	public org.citygml4j.core.model.bridge.BridgeConstructiveElement getGmlObject() {
		return gmlBridgeElement;
	}

	@Override
	public void unsetGmlGeometries() {
		gmlBridgeElement.setLod0MultiSurface(null);
		gmlBridgeElement.setLod2MultiSurface(null);
		gmlBridgeElement.setLod3MultiSurface(null);
		DeprecatedPropertiesOfBridgeConstructiveElement depProps = gmlBridgeElement.getDeprecatedProperties();
		depProps.setLod1Geometry(null);
		depProps.setLod2Geometry(null);
		depProps.setLod3Geometry(null);
		depProps.setLod4Geometry(null);
		gmlBridgeElement.setLod1Solid(null);
		gmlBridgeElement.setLod2Solid(null);
		gmlBridgeElement.setLod3Solid(null);
		for (BoundarySurface bs : boundarySurfaceList) {
			bs.unsetGmlGeometries();
		}
	}

	@Override
	public FeatureType getFeatureType() {
		return FeatureType.BRIDGE_CONSTRUCTION_ELEMENT;
	}

	public void addBoundarySurface(BoundarySurface bs) {
		boundarySurfaceList.add(bs);
		bs.setParent(this);
	}
	
	public List<BoundarySurface> getBoundarySurfaces() {
		return boundarySurfaceList;
	}
	
	@Override
	public void prepareForChecking() {
		super.prepareForChecking();
		for (BoundarySurface bs : boundarySurfaceList) {
			bs.prepareForChecking();
		}
	}
	
	@Override
	public void clearMetaInformation() {
		super.clearMetaInformation();
		for (BoundarySurface bs : boundarySurfaceList) {
			bs.clearMetaInformation();
		}
	}
	
	@Override
	public void collectInstances(CopyHandler handler) {
		super.collectInstances(handler);
		handler.addInstance(boundarySurfaceList);
	}
	
	@Override
	public void fillValues(Copyable original, CopyHandler handler) {
		super.fillValues(original, handler);
		BridgeConstructiveElement originalBce = (BridgeConstructiveElement) original;
		for (BoundarySurface originalBs : originalBce.boundarySurfaceList) {
			boundarySurfaceList.add(handler.getCopyInstance(originalBs));
		}
	}

}
