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

public class Seguir : MonoBehaviour
{
    public bool sigue = false;
    public Material seguidor;
    public float factorAtraccion = 0.9f;
    public float factorPadre = 0.1f;
    public float factorDeambulante = 1000;
    public float MaxDist = 10f;
    Transform Player;
    bool moviendo;

    Mover padre;
    Vector3 movRandom;
    Vector3 fuerzaAtraccion;
    Vector3 distancia;
    Vector3 movPadre;
    MeshRenderer meshRender;
    private float creacion;

    public Text textoContador;

    void Start()
    {
        factorDeambulante = 1000;
        moviendo = true;
        movRandom = Vector3.zero;
        movPadre = Vector3.zero;
        creacion = Random.value * 10;
        padre = GameObject.FindGameObjectWithTag("Player").GetComponent<Mover>();
        Player = GameObject.FindGameObjectWithTag("Player").transform;

    }

    // Update is called once per frame
    void FixedUpdate()
    {

        if (Vector3.Distance(transform.position, Player.position) < MaxDist && !sigue)
        {
            Escuchando();
        }
        else if (sigue)
        {
            Siguiendo();
        }

        else if (moviendo)
        {
            Deambular();
        }
        

    }

    public void Convertir()
    {
        sigue = true;
        transform.eulerAngles = new Vector3(-90, 0, 0);
    }

    public void ToggleMove()
    {
        moviendo = !moviendo;
    }

    void Deambular()
    {
        float h = Mathf.PerlinNoise(creacion, Time.time / factorDeambulante) - 0.5f;
        float v = Mathf.PerlinNoise(creacion+1, Time.time / factorDeambulante) - 0.5f;

        movRandom = new Vector3(h, 0, v);

        transform.position += movRandom;
    }

    void Siguiendo()
    {
        factorDeambulante = 10;

        float h = Mathf.PerlinNoise(creacion, Time.time / factorDeambulante) - 0.5f;
        float v = Mathf.PerlinNoise(creacion+1, Time.time / factorDeambulante) - 0.5f;

        movRandom = new Vector3(h, 0, v);

        distancia = (padre.transform.position - transform.position);
        fuerzaAtraccion = factorAtraccion * Mathf.Sqrt(distancia.magnitude) * distancia * Time.deltaTime;

        movPadre = padre.velocidad * factorPadre;

        transform.position += fuerzaAtraccion + movPadre + movRandom;
    }

    void Escuchando()
    {
        transform.LookAt(Player);
        transform.Rotate(-90, 0, 0);
    }

}
