using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;

public class NetworkTrail : NetworkBehaviour
{
    public TrailRenderer trail;
    public LineRenderer line;
    public bool enableValidation = true;
    public int maxDetourPoints = 1;
    public float DetourThreshold = 1;
    public int Detours;

    public Vector3[] positions;

    void Start()
    {
        //trail.gameObject.SetActive(isServer);
        line.gameObject.SetActive(!isServer);
        line.transform.parent=null;
        line.transform.position =Vector3.zero;
    }

    // Update is called once per frame
    void Update()
    {
        if(isServer){
            positions = new Vector3[trail.positionCount];
            trail.GetPositions(positions);
            RpcUpdatePositions(positions);
        }else{

        }
    }


    [ClientRpc]
    void RpcUpdatePositions(Vector3[] Positions){
        if(!enableValidation){return;}
        positions = Positions;
        line.positionCount = positions.Length;
        line.SetPositions(positions);

        //Validate With Trail
        Vector3[] localPositions = new Vector3[trail.positionCount];
        trail.GetPositions(localPositions);
        Detours = 0;
        for(int i=0; i < Positions.Length; i++){
            bool pointValidated = false;
            for(int j=1; j < 3; j++){
                try{
                if(isCloseEnough(Positions[i], localPositions[i+j])){
                    pointValidated = true;
                    break;
                }
                if(isCloseEnough(Positions[i], localPositions[i-j])){
                    pointValidated = true;
                    break;
                }

                }catch{
                    //No local position, Hence, no validation
                }
            }
            if(!pointValidated){
                Detours++;
            }
        }

        if(Detours > maxDetourPoints){
            //Too much detours, Set back to servers data
            trail.SetPositions(Positions);
        }
    }

    bool isCloseEnough(Vector3 a, Vector3 b){
        return Vector3.Distance(a,b) < DetourThreshold;
    }
}
