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

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

import de.hft.stuttgart.citydoctor2.datastructure.LinearRing;
import de.hft.stuttgart.citydoctor2.datastructure.Polygon;

/**
 * A two dimensional polygon. Has an 2d exterior ring and interior rings
 * 
 * @author Matthias Betz
 *
 */
public class Polygon2d {

	private Ring2d exterior;
	private List<Ring2d> innerRings;

	public static Polygon2d withProjection(Polygon poly) {
		ProjectionAxis axis = ProjectionAxis.of(poly);
		return projectTo2D(poly, axis);
	}

	public static Polygon2d withProjection(MovedPolygon poly, ProjectionAxis projectionAxis) {
		return projectTo2D(poly, projectionAxis);
	}

	public static Polygon2d withProjection(Polygon poly, ProjectionAxis projectionAxis) {
		return projectTo2D(poly, projectionAxis);
	}

	private static Polygon2d projectTo2D(Polygon p, ProjectionAxis axis) {
		List<Ring2d> interior = new ArrayList<>();
		Ring2d exterior = Ring2d.of(p.getExteriorRing(), axis);
		for (LinearRing innerRing : p.getInnerRings()) {
			interior.add(Ring2d.of(innerRing, axis));
		}
		return new Polygon2d(exterior, interior);
	}

	private static Polygon2d projectTo2D(MovedPolygon p, ProjectionAxis axis) {
		List<Ring2d> interior = new ArrayList<>();
		Ring2d exterior = Ring2d.of(p.getExteriorRing(), axis);
		for (MovedRing innerRing : p.getInnerRings()) {
			interior.add(Ring2d.of(innerRing, axis));
		}
		return new Polygon2d(exterior, interior);
	}

	/**
	 * Converts a Polygon to a 2d polygon. This will change the area of the polygon.
	 * 
	 * @param ring a linear ring
	 */
	private Polygon2d(Ring2d exterior, List<Ring2d> interior) {
		if (interior == null) {
			interior = Collections.emptyList();
		}
		this.exterior = exterior;
		this.innerRings = interior;
	}

	public Ring2d getExterior() {
		return exterior;
	}

	public List<Ring2d> getInteriorRings() {
		if (innerRings == null) {
			return Collections.emptyList();
		}
		return innerRings;
	}

}
