using System;
using System.Collections.Generic;
using System.Windows.Media.Media3D;
using MediaColor = System.Windows.Media.Color;
using Point2D = System.Windows.Point;

namespace AvengersUtd.Test
{
    public static class MathHelper
    {
        public static Vector3D CalculateNormal(Point3D p0, Point3D p1, Point3D p2)
        {
            Vector3D v0 = new Vector3D(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
            Vector3D v1 = new Vector3D(p2.X - p1.X, p2.Y - p1.Y, p2.Z - p1.Z);
            return Vector3D.CrossProduct(v0, v1);
        }

        public static MeshGeometry3D BuildMesh(Point3D p0, Point3D p1, Point3D p2, Point3D p3,
            Point2D t0, Point2D t1, Point2D t2, Point2D t3)
        {
            MeshGeometry3D mesh = new MeshGeometry3D();
            mesh.Positions.Add(p0);
            mesh.Positions.Add(p1);
            mesh.Positions.Add(p2);
            mesh.Positions.Add(p3);

            Vector3D normal = CalculateNormal(p0, p1, p2);
            mesh.TriangleIndices.Add(0);
            mesh.TriangleIndices.Add(1);
            mesh.TriangleIndices.Add(2);
            mesh.Normals.Add(normal);
            mesh.Normals.Add(normal);
            mesh.Normals.Add(normal);
            mesh.TextureCoordinates.Add(t3);
            mesh.TextureCoordinates.Add(t2);
            mesh.TextureCoordinates.Add(t1);

            normal = CalculateNormal(p2, p3, p0);
            mesh.TriangleIndices.Add(2);
            mesh.TriangleIndices.Add(3);
            mesh.TriangleIndices.Add(0);
            mesh.Normals.Add(normal);
            mesh.Normals.Add(normal);
            mesh.Normals.Add(normal);
            mesh.TextureCoordinates.Add(t0);
            mesh.TextureCoordinates.Add(t1);
            mesh.TextureCoordinates.Add(t2);

            mesh.Freeze();
            return mesh;
        }
        public static Geometry3D Tessellate()
        {
            Point3D p0 = new Point3D(-1, -1, 0);
            Point3D p1 = new Point3D(1, -1, 0);
            Point3D p2 = new Point3D(1, 1, 0);
            Point3D p3 = new Point3D(-1, 1, 0);
            Point2D t0 = new Point2D(0, 0);
            Point2D t1 = new Point2D(1, 0);
            Point2D t2 = new Point2D(1, 1);
            Point2D t3 = new Point2D(0, 1);
            return BuildMesh(p0, p1, p2, p3, t0, t1, t2, t3);
        }

        public static Geometry3D TessellateMirror()
        {
            Point3D p0 = new Point3D(-1, -3, 0);
            Point3D p1 = new Point3D(1, -3, 0);
            Point3D p2 = new Point3D(1, -1, 0);
            Point3D p3 = new Point3D(-1, -1, 0);
            Point2D t0 = new Point2D(0, 1);
            Point2D t1 = new Point2D(1, 1);
            Point2D t2 = new Point2D(1, 0);
            Point2D t3 = new Point2D(0, 0);
            return BuildMesh(p0, p1, p2, p3, t0, t1, t2, t3);
        }
    }
}
