using UnityEngine;
using System.Collections.Generic;

/*
 * Abstract class representing SlicedPolygons in the game
*/
public abstract class GamePolygon : GameMesh {

    protected SlicedPolygon slicedPolygon;

    public GamePolygon(SlicedPolygon slicedPolygon) {
        this.slicedPolygon = slicedPolygon;
    }

    public GamePolygon(CheesePolygon cheesePolygon) : this(new SlicedPolygon(cheesePolygon)) { }

    public GamePolygon(Contour contour) : this(new CheesePolygon(contour)) { }

    //In case the polygon is modified, call this method
    public void update(SlicedPolygon slicedPolygon) {
        this.slicedPolygon = slicedPolygon;

        if (isAddedToGame) {
            Object.Destroy(gameObject);
            addToGame();
        }
    }

    public void update(Contour contour) {
        update(new SlicedPolygon(contour));
    }

    // Call this method to create the mesh and add it to the game
    public override void addToGame() {
        base.addToGame();

        List<int> indices;
        List<Vector3> vertices;
        Triangulation.triangulateForDisplay(this, z, out indices, out vertices);        

        // Create the mesh
        Mesh mesh = new Mesh();
        mesh.vertices = vertices.ToArray();
        mesh.triangles = indices.ToArray();
		mesh.uv = generateUV(vertices);
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();

        filter.mesh = mesh;
    }

	virtual protected Vector2[] generateUV(List<Vector3> vertices) {
		Vector2[] uv = new Vector2[vertices.Count];
		for (int j = 0; j < uv.Length; j++) {
			uv[j] = new Vector2(vertices[j].x / 1000, vertices[j].y / 1000); //TODO : remove magic number

		}

		return uv;
	}

    public SlicedPolygon getSlicedPolygon() {
        return slicedPolygon;
    }

    public bool isPointInside(GameVertex point) {
        return slicedPolygon.isPointInside(point);
    }
}
