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

public class WindController : MonoBehaviour{

    PlayerController player;
    CanvasManager canvas;
    SpawnerManager spawner;

    [SerializeField] AudioSource windSource;
    [Range(0, 1)] [SerializeField] float windyVolume;
    [Range(0, 1)] [SerializeField] float defaultVolume;
    float velocity;
    bool windy;

    [Space]
    [SerializeField] GameObject wind;
    [SerializeField] float playerMoveDelay = 2f;
    [SerializeField] float windDuration = 1f;

    Vector3 randomDirection;

    // Start is called before the first frame update
    void Awake(){
        player = FindObjectOfType<PlayerController>();
        canvas = FindObjectOfType<CanvasManager>();
        spawner = FindObjectOfType<SpawnerManager>();
    }

    void Start(){
        canvas.onWind.AddListener(() => MovePlayer());
    }

    void Update(){
        if (windy){
            windSource.volume = Mathf.SmoothDamp(windSource.volume, windyVolume, ref velocity, .5f);
        }else{
            windSource.volume = Mathf.SmoothDamp(windSource.volume, defaultVolume, ref velocity, .5f);
        }
    }

    void MovePlayer(){
        canvas.WindStart();
        randomDirection = GenerateRandomDirection();
        wind.transform.LookAt(randomDirection.normalized);
        wind.transform.rotation = Quaternion.Euler(wind.transform.eulerAngles.x, wind.transform.eulerAngles.y - 90, wind.transform.eulerAngles.z);
        wind.SetActive(true);
        player.StartWind();
        StartCoroutine(DisableWind());
        windy = true;
    }

    Vector3 GenerateRandomDirection(){
        Vector3[] axis = new Vector3[8];
        axis[0] = Vector3.right * 1.25f;
        axis[1] = Vector3.left * 1.25f;
        axis[2] = Vector3.forward * 1.25f;
        axis[3] = Vector3.back * 1.25f;
        axis[4] = new Vector3(1.25f, 0, 1.25f);
        axis[5] = new Vector3(-1.25f, 0, 1.25f);
        axis[6] = new Vector3(1.25f, 0, -1.25f);
        axis[7] = new Vector3(-1.25f, 0, -1.25f);

        return axis[Random.Range(0, 7)];
    }

    IEnumerator DisableWind(){
        yield return new WaitForSeconds(playerMoveDelay);
        player.MoveWind(randomDirection, Mathf.RoundToInt(Random.Range(50, 149) / 50));
        spawner.StartCoroutine(spawner.Spawn());
        yield return new WaitForSeconds(windDuration);
        windy = false;
        wind.SetActive(false);
        player.EndWind();
        canvas.WindStop();
    }
}
