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

public class SpawnerOnSpline : MonoBehaviour {

    [SerializeField]
    protected Vector2 minMaxOffset = new Vector2(-2, 2);
    protected EnvironmentSetup environment;
    protected Transform objectsParent;

    protected virtual string ObjectsParentName { get { return "Object parent"; } }
    
    
    protected virtual void Awake()
    {
        SetupVars();
    }

    bool varsSetup = false;
    protected void SetupVars()
    {
        if (varsSetup)
            return;
        // Get spline.
        environment = GetComponent<EnvironmentSetup>();
        if (environment == null)
            return;

        // Create objectsParent.
        if (transform.Find(ObjectsParentName) == null)
        {
            GameObject newObjectsParent = new GameObject(ObjectsParentName);
            objectsParent = newObjectsParent.transform;
            objectsParent.parent = transform;
        }
        else
        {
            objectsParent = transform.Find(ObjectsParentName);
        }
        varsSetup = true;
    }

    protected void SpawnObjectOnSpline(Transform tr, float splineProgress)
    {
        // Spawn a transform on our spline, with a random offset perpendicular to the spline.
        Transform newTR = Instantiate(tr, objectsParent);
        Vector3 onSplinePosition = environment.Spline.GetPoint(splineProgress);
        float randomXOffset = Random.Range(minMaxOffset.x, minMaxOffset.y);
        Vector3 offset = Quaternion.Euler(0, 90, 0) * environment.Spline.GetDirection(splineProgress);
        offset *= randomXOffset;
        tr.position = onSplinePosition + offset;
    }
}
