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

public class RenderParcours : MonoBehaviour
{
    public Transform MyParent;
    public Material LineMaterial;
    public ConfigReader Config;
    void Start()
    {
        GetParcoursData();
    }

    void GetParcoursData()
    {
        /** "LineWidth" : 0.1, 
		"Kind" : "PieceWise",	
		"LinePieces" : [
			{ "x" : 1.1, "y" : 12.2},
			{ "x" : 1.43, "y" : 4.5},
			{ "x" : 1.8, "y" : 3.5},
			{ "x" : 1.1, "y" : 2.5}
			]**/
        if (Config.configuration.Parcours.Kind == "PieceWise")
        {
            ConfigLinePieces[] lps = Config.configuration.Parcours.LinePieces;
            int AmntLinePieces = lps.Length / 2; // Length should have been checked by ConfigReader.ValidParcours() already
            for (int i = 0; i < AmntLinePieces; i++)
            {
                GameObject Renderer = new GameObject();
                Renderer.transform.SetParent(MyParent);
                LineRenderer lr = Renderer.AddComponent<LineRenderer>();
                PrepareLR(lr, Renderer);
                lr.widthCurve = AnimationCurve.Constant(0.0f, 1f, Config.configuration.Parcours.LineWidth);
                Vector3[] posvector = new Vector3[2];
                posvector[0] = new Vector3(lps[i*2].x, lps[i*2].y, 0f);
                posvector[1] = new Vector3(lps[i * 2 + 1].x, lps[i * 2 + 1].y, 0f);
                lr.positionCount = posvector.Length;
                lr.SetPositions(posvector);
            }
        }
        else if (Config.configuration.Parcours.Kind == "Trail")
        {
            GameObject Renderer = new GameObject();
            Renderer.transform.SetParent(MyParent);
            LineRenderer lr = Renderer.AddComponent<LineRenderer>();
            PrepareLR(lr, Renderer);
            lr.widthCurve = AnimationCurve.Constant(0.0f, 1f, Config.configuration.Parcours.LineWidth);
            ConfigLinePieces[] lps = Config.configuration.Parcours.LinePieces;
            Vector3[] posvector = new Vector3[lps.Length];

            for (int i = 0; i < lps.Length; i++)
            {
                posvector[i] = new Vector3(lps[i].x, lps[i].y, 0f);
            }
            lr.positionCount = posvector.Length;
            lr.SetPositions(posvector);
        }
    }
    void PrepareLR(LineRenderer lr, GameObject Renderer)
    {
        lr.alignment = LineAlignment.TransformZ;
        lr.material = LineMaterial;
        lr.textureMode = LineTextureMode.Stretch;
        lr.useWorldSpace = false;
        lr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
        Renderer.transform.localPosition = new Vector3(0, 0, -0.0001f);
        Renderer.transform.localRotation = Quaternion.identity;
        lr.generateLightingData = true;
        lr.numCornerVertices = 3;
        lr.numCapVertices = 3;
    }
}
