using Newtonsoft.Json;
using REST_JSON_API;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

/// <summary>
/// Point in 3D Space
/// </summary>
public class TriangleFact2 : FactWrappedCRTP<TriangleFact2>
{


    //used points
    public string PidA, PidB, PidC;

    public Vector3 A, B, C, a, b, c;

    public float cPosition;

    public float Area = 0.0F;



    public PointFact GetA {get =>  (PointFact)FactRecorder.AllFacts[PidA];}
    public PointFact GetB {get =>  (PointFact)FactRecorder.AllFacts[PidB];}
    public PointFact GetC {get =>  (PointFact)FactRecorder.AllFacts[PidC];}
    protected void calculate_vectors(){

        A = ((PointFact)FactRecorder.AllFacts[PidA]).Point + Vector3.zero;
        B = ((PointFact)FactRecorder.AllFacts[PidB]).Point + Vector3.zero;
        C = ((PointFact)FactRecorder.AllFacts[PidC]).Point + Vector3.zero;
        a = B + Vector3.Project(A - B, C - B);
        b = C + Vector3.Project(B - C, A - C);
        c = A + Vector3.Project(C - A, B - A);

        cPosition = Vector3.Distance(A, c) / Vector3.Distance(A, B);

        Area = 0.5f * (Vector3.Distance(A, B) * Vector3.Distance(c, C));

        Vector3 scale = new Vector3(Vector3.Distance(A, B), Vector3.Distance(c, C), 1.0F);
        
        LocalScale = scale;

        /*
        Vector3 lineVec3 = B - A;
        Vector3 crossVec1And2 = Vector3.Cross(a - A, b - B);
        Vector3 crossVec3And2 = Vector3.Cross(lineVec3, b - B);
        float planarFactor = Vector3.Dot(lineVec3, crossVec1And2);
        Vector3 intersection;
        if(Mathf.Abs(planarFactor) < 0.0001f && crossVec1And2.sqrMagnitude > 0.0001f)
        {
            float s = Vector3.Dot(crossVec3And2, crossVec1And2) / crossVec1And2.sqrMagnitude;
            intersection = A + ((a - A) * s);
        } else
        {
            intersection = Vector3.zero;
        }
        Position =  intersection;
        */

        Position = A;

        Rotation = Quaternion.LookRotation(Vector3.Cross((B - A), (C - A)), Vector3.up);
        //Rotation = Quaternion.LookRotation(forward, new Vector3(1.0F, 0.0F, 0.0F));
        
    }

    public TriangleFact2() : base(){
        this.PidA = null;
        this.PidB = null;
        this.PidC = null;
    }
    [JsonConstructor]
    public TriangleFact2( string PidA, string PidB, string PidC) : base()
    {
        this.PidA = PidA;
        this.PidB = PidB;
        this.PidC = PidC;

        calculate_vectors();
    }

    /// <summary>
    /// Bypasses initialization of new MMT %Fact by using existend URI, _which is not checked for existence_.
    /// <see cref="Normal"/> set to <c>Vector3.up</c>
    /// </summary>
    /// <param name="Point">sets <see cref="Point"/></param>
    /// <param name="ServerDefinition">MMT URI as OMS</param>
    public TriangleFact2(string PidA, string PidB, string PidC, SOMDoc ServerDefinition) : base()
    {
        this.PidA = PidA;
        this.PidB = PidB;
        this.PidC = PidC;
        
        this.ServerDefinition = ServerDefinition;

        calculate_vectors();
    }

    /// \copydoc Fact.parseFact(ScrollFact)
    public new static IEnumerator parseFact(List<Fact> ret, MMTFact fact)
    {
        if (((MMTGeneralFact)fact).defines is not OMA df)
            yield break;

        OMS pointA, pointB, pointC;

        pointA = (OMS)df.arguments[0];
        pointB = (OMS)df.arguments[1];
        pointC = (OMS)df.arguments[2];

        string PidA = pointA.uri;
        string PidB = pointB.uri;
        string PidC = pointC.uri;

        

        ret.Add(new TriangleFact2(PidA, PidB, PidC));

        //ParsingDictionary.parseTermsToId.TryAdd(defines.ToString(), fact.@ref.uri);
        //ret.Add(new PointFact(SOMDoc.MakeVector3(defines), fact.@ref));
    }


    /// \copydoc Fact.hasDependentFacts
    public override bool HasDependentFacts => true;

    /// \copydoc Fact.getDependentFactIds
    protected override string[] GetDependentFactIds()
        => new string[] { PidA, PidB, PidC};

    /// \copydoc Fact.GetHashCode
    /* public override int GetHashCode()
        => this.Point.GetHashCode();
    */
    protected override void RecalculateTransform()
    {
        calculate_vectors();
    }
    /// \copydoc Fact.Equivalent(Fact, Fact)
    protected override bool EquivalentWrapped(TriangleFact2 f1, TriangleFact2 f2){
        
        return (

                    Math3d.IsApproximatelyEqual(f1.A, f2.A)
                && Math3d.IsApproximatelyEqual(f1.B, f2.B)
                && Math3d.IsApproximatelyEqual(f1.C, f2.C)
                && Math3d.IsApproximatelyEqual(f1.c, f2.c)

        );

    }

    protected override Fact _ReInitializeMe(Dictionary<string, string> old_to_new){
        
        return new TriangleFact2(this.PidA, this.PidB, this.PidC);

    }

    public override MMTFact MakeMMTDeclaration()
    {
        SOMDoc tp = new OMS(MMTConstants.TriangleType);

        return new MMTGeneralFact(_LastLabel, tp, Defines());
    }

    public override SOMDoc Defines()
        => new OMA(
                new OMS(MMTConstants.TriangleCons),
                new[] {
                        new OMS(PidA),
                        new OMS(PidB),
                        new OMS(PidC),
                }
            );
}