using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class WavePlatform : MonoBehaviour {

    public Mr1.PathData Path;
    public bool Autostart=false,Push=false;
    public float Speed;
    bool moving;
    int index;
    Vector3 lastPos;
    public Transform player,center;

	void Start () {
        lastPos = Vector3.zero;
        center = transform.FindChild("Center");
        Reset();
	}
	
	void Update () {
		if(Autostart && Path != null) {
            if(moving) return;
            Vector3[] path = Path.points.ToArray();
            for(int i = 0; i < path.Length; i++) {
                path[i].y = transform.position.y;
            }
            transform.DOPath(path,Speed).SetSpeedBased(true).SetLoops(-1,LoopType.Yoyo);
            moving = true;
        }
	}
    /*
    void FixedUpdate() {
        if(Autostart && Push && Path != null) {
            if(player == null) return;
            Vector3 center = new Vector3(transform.position.x,player.position.y,transform.position.z)+new Vector3(Random.Range(0f,0.01f),Random.Range(0f,0.01f),Random.Range(0f,0.01f));
            float dist = 1f+Vector3.Distance(center,player.position);
            Vector3 fugal = (center - player.position);
            player.Translate(fugal/factor);
        }
    }
    */
    void LateUpdate() {
        if(Autostart && Path != null) {
            Vector3 newpos = transform.position;
            Vector3 offset = newpos-lastPos;
            if(player != null)
                player.position += offset;
            lastPos = newpos;
        }
    }

    void OnCollisionEnter(Collision col) {
        //if(Autostart) return;
        //Debug.Log(col.gameObject.name);
        if(col.gameObject.CompareTag("Player")) {
            /* UnityStandardAssets.Characters.FirstPerson.FirstPersonController fps = col.gameObject.GetComponent<UnityStandardAssets.Characters.FirstPerson.FirstPersonController>();
            if(fps != null) {
                fps.m_JumpSpeed = 0f;
            }
            Autostart = true;
            moving = false;
            index = 0; */
            player = col.gameObject.transform;
            if(Time.realtimeSinceStartup > 5f) AudioManager.Get.PlaySFX("Success" + Random.Range(1,3));
            player.position = new Vector3(center.position.x,player.position.y,center.position.z);
        }
    }

    void OnCollisionExit(Collision col) {
        player = null;
    }

    public void Reset() {
        if(Path == null) return;
        transform.position = Path.points[0];
        DOTween.Kill(transform);
        moving = false;
    }
}
