using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using OpenTK;

namespace ObjectManager
{
    public class Face
    {
        public List<FaceVertex> Vertices;

        #region Constructors

        public Face(FaceVertex[] vertices)
        {
            this.Vertices = new List<FaceVertex>(vertices);
        }

        public Face()
        {
            this.Vertices = new List<FaceVertex>();
        }

        public Face(Face face)
        {
            this.Vertices = new List<FaceVertex>(face.Vertices);
        }

        #endregion

        #region Methods

        public void CreateNormals()
        {
            if (this.Vertices.Count >= 3)
            {
                double ax = this.Vertices[1].Vertex.Coordinates.X - this.Vertices[0].Vertex.Coordinates.X;
                double ay = this.Vertices[1].Vertex.Coordinates.Y - this.Vertices[0].Vertex.Coordinates.Y;
                double az = this.Vertices[1].Vertex.Coordinates.Z - this.Vertices[0].Vertex.Coordinates.Z;
                double bx = this.Vertices[2].Vertex.Coordinates.X - this.Vertices[0].Vertex.Coordinates.X;
                double by = this.Vertices[2].Vertex.Coordinates.Y - this.Vertices[0].Vertex.Coordinates.Y;
                double bz = this.Vertices[2].Vertex.Coordinates.Z - this.Vertices[0].Vertex.Coordinates.Z;
                double nx = ay * bz - az * by;
                double ny = az * bx - ax * bz;
                double nz = ax * by - ay * bx;
                double t = nx * nx + ny * ny + nz * nz;
                if (t != 0.0)
                {
                    t = 1.0 / Math.Sqrt(t);
                    double mx = (nx * t);
                    double my = (ny * t);
                    double mz = (nz * t);
                    for (int j = 0; j < this.Vertices.Count; j++)
                    {
                        if (this.Vertices[j].Normals == Vector3d.Zero)
                        {
                            this.Vertices[j].Normals = new Vector3d(mx, my, mz);
                        }
                    }
                }
                else
                {
                    for (int j = 0; j < this.Vertices.Count; j++)
                    {
                        if (this.Vertices[j].Normals == Vector3d.Zero)
                        {
                            this.Vertices[j].Normals = new Vector3d(0.0, 1.0, 0.0);
                        }
                    }
                }
            }
        }

        #endregion
    }
}
