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

public class ElevatorScript : MonoBehaviour, Velocitor
{

    public List<GameObject> positions;
    public bool enab;
    public float speed;
    public float delayBeforeMove;

    Vector3 offset;
    Vector3 lastmove;
    float currentDelay;
    bool nextPoint;
    int curridx; // mod len(positions)*2 - 2

    public void Awake()
    {
        if (speed == 0) speed = 0.02f;
        GameObject go = new GameObject();
        go.transform.position = positions[0].transform.position;
        positions[0] = go;
        offset = transform.position - positions[0].transform.position;
        currentDelay = delayBeforeMove;
        nextPoint = true;
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if (positions.Count < 2) return;
        if (!nextPoint) return;
        if(enab)
        {
            //print("mo");
            int actualcurridx = curridx;
            if (actualcurridx >= positions.Count) actualcurridx = 2 * positions.Count - actualcurridx - 2;

            Vector3 wannabe = positions[actualcurridx].transform.position+offset;
            Vector3 v = (wannabe - transform.position).normalized;
            float l2l1 = Mathf.Max(Mathf.Abs(v.x), Mathf.Abs(v.y)); // this is so speed is speed along the longer direction
            Vector3 poso = transform.position;
            Vector3 newposo = Vector3.MoveTowards(transform.position, wannabe, speed / l2l1);
            GetComponent<Rigidbody2D>().MovePosition(newposo);
            lastmove = newposo - poso;

            if(Vector2.Distance(transform.position, wannabe) < 0.1f)
            {
                curridx += 1;
                if (curridx >= positions.Count * 2 - 2)
                {
                    curridx = 0;
                }
                currentDelay = delayBeforeMove;
            }
        }
    }

    void Update()
    {
        if (currentDelay > 0)
        {
            currentDelay -= Time.deltaTime;
            if (currentDelay <= 0) nextPoint = true;
        }
    }

    public Vector3 GetVelocity()
    {
        return lastmove;
    }
}
