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

public class PlayerScript : MonoBehaviour
{

    public GameObject victoryScreen;
    public GameObject gameoverScreen;
    public GameObject noteParticle;

    Transform tomatoLauncher;


    CharacterController character;
    public float speed;
    float currentlyDisplayedScore;
    
    public bool canMove;

     public Texture[] frontRun, backRun, rightRun, leftRun, idle, hardDance, loose, victory;

    Texture[] currentTextures;
    public int animCounter;

    public Renderer myRenderer;

    public Image jaugeSuccessImage;

    float texturechrono;
    public AudioClip victorySound, gameoverSound;

    public AudioClip[] triggerBoo, triggerOvation;

    enum Animation {frontRun, backRun, leftRun, rightRun, idle, hardDance, loose, victory};

    Animation currentAnim;

    public static bool hardDancing;

    public static float success;

    public static bool isPlaying;

    public GameObject tomate, rose;

    float idleTimer;

    public Text monitoringText;

    float successLastFrame;

    Transform foule;


public AudioSource crowdFort, crowdMoyen, crowdNul, MusiqueA, MusiqueB, MusiqueC, MusiqueIntro;
float musiqueBVolume;
float musiqueCVolume;

    void Awake()
    {
        tomatoLauncher = GameObject.Find("TomatoLauncher").transform;
        tomatoLauncher.gameObject.SetActive(false);
        character = GetComponent<CharacterController>();
        texturechrono = 0;
        animCounter = 0;
        currentAnim = Animation.idle;
        hardDancing = false;
        success = 50f;
        currentlyDisplayedScore = success;
        crowdFort.volume = crowdNul.volume = 0;
        crowdMoyen.volume = 0.5f;
        gameoverScreen.SetActive(false);
        victoryScreen.SetActive(false);
        if (GameObject.Find("FOULE")) foule = GameObject.Find("FOULE").transform;
    }

    public void NewGame()
    {
        MusiqueIntro.Stop();
        gameoverScreen.SetActive(false);
        victoryScreen.SetActive(false);
        success = 50f;
        canMove = true;
        isPlaying = true;
        texturechrono = 0;
        animCounter = 0;
        currentAnim = Animation.idle;
        transform.position = new Vector3(0,0.5f, -3f);
        MusiqueA.Play();
        MusiqueB.Play();
        MusiqueC.Play();
        successLastFrame = success;
    }



    void Update()
    {
        texturechrono += Time.deltaTime;

        if (canMove) PlayerMovement();
     
        if (isPlaying)
        {
            TomatoLauncher();
            RoseLauncher();
            UpdateSuccess();
            SoundMix(MusiqueB, musiqueBVolume);
            SoundMix(MusiqueC, musiqueCVolume);
        }
        else
        {

        }

        NewTexture();
        Monitoring();

        successLastFrame = success;
    }

    void SoundMix(AudioSource desiredTrack, float desiredVolume)
    {
        if (desiredTrack.volume < desiredVolume)
        {
           desiredTrack.volume += 8f*Time.deltaTime;
        }
        else if (desiredTrack.volume > desiredVolume + 0.02f)
        {
            desiredTrack.volume -= 2f*Time.deltaTime;
        }
    }



    void Monitoring()
    {
        monitoringText.text = "crowdFort : "+ (crowdFort.volume*100f).ToString("F0") + "\n"+"crowdMoyen : " + (crowdMoyen.volume*100f).ToString("F0")+"\n"+"crowdNul : "+(crowdNul.volume*100f).ToString("F0");
    }

    void PlayerMovement()
    {
        Vector3 movement = Vector3.ClampMagnitude(new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")), 1f) * speed*Time.deltaTime;
        
        if (transform.position.z < -4.7f && movement.z < 0) movement.z = 0;
        if (transform.position.z > -0.3f && movement.z > 0) movement.z = 0;
        if (transform.position.x < -7f && movement.x < 0) movement.x = 0;
        if (transform.position.x > 7f && movement.x > 0) movement.x = 0;

        if (movement.magnitude > 0.01f)
        {
            EndOvation();
            idleTimer = 0;
            musiqueBVolume = 0;
            musiqueCVolume = 0;
            success -= 20f*Time.deltaTime;

            if (Mathf.Abs(movement.x) > Mathf.Abs(movement.z))
            {
                if (movement.x>0) currentAnim = Animation.rightRun;
                else currentAnim = Animation.leftRun;  
            } 
            else
            {
                if (movement.z > 0) currentAnim = Animation.backRun;
                else currentAnim = Animation.frontRun;
            }            
        }
        else
        {
            idleTimer += Time.deltaTime;
            musiqueBVolume = 1f;

            if (hardDancing) success += 50f*Time.deltaTime; else success += 3f*Time.deltaTime;

            if (currentAnim != Animation.idle && currentAnim!= Animation.hardDance)
            {
                texturechrono = 0;
                if (hardDancing)
                {
                    musiqueCVolume = 1f;
                    StartOvation();
                    currentAnim = Animation.hardDance;
                }
                else
                {
                    musiqueCVolume = 0f;
                    EndOvation();
                    currentAnim = Animation.idle;
                }

            }

            else
            {
                if (currentAnim == Animation.idle && hardDancing)
                {
                    StartOvation();
                    currentAnim = Animation.hardDance;
                }
                else if (!hardDancing)
                {
                    EndOvation();
                    currentAnim = Animation.idle;
                }
            }
        }
        




        movement += -9.81f*Vector3.up*Time.deltaTime;
        character.Move(movement);
    }



    void NewTexture()
    {
        switch(currentAnim)
        {
                case Animation.idle : 
                currentTextures = idle;
                break;

                case Animation.frontRun : 
                currentTextures = frontRun;
                break;

                case Animation.backRun : 
                currentTextures = backRun;
                break;

                case Animation.leftRun : 
                currentTextures = leftRun;
                break;

                case Animation.rightRun : 
                currentTextures = rightRun;
                break;

                case Animation.hardDance:
                currentTextures = hardDance;
                break;

                case Animation.loose:
                currentTextures = loose;
                break;

                case Animation.victory:
                currentTextures = victory;
                break;

        }

        if (texturechrono > 0.1f)
        {
            animCounter +=1;
            if (animCounter > currentTextures.Length - 1) animCounter = 0;
            ChangeSprite(currentTextures[animCounter]);
            texturechrono = 0;
        }        

    }
    void ChangeSprite(Texture newSprite)
    {
        myRenderer.material.SetTexture("_MainTex", newSprite);
    }


    float noteTimer = 0;
    float desiredNoteTimer = 0;
    void UpdateSuccess()
    {
        noteTimer+= Time.deltaTime;

        crowdNul.volume = (-1f/40f)*success + 1f;
        crowdMoyen.volume = (1f/20f)*success - 0.25f;
        crowdFort.volume = (1/30f)*success - (7f/3f);

        if (success<0)
        {
            success = 0;
            GameOver();
        } 
        if (success> 100f)
        {
            success = 100f;
        }

        if (successLastFrame > 20f && success < 20f)
        {
            PlayRandomSound(triggerBoo);
        }
        if (successLastFrame < 100f && success == 100f)
        {
            PlayRandomSound(triggerOvation);
        }

        if (currentlyDisplayedScore < success)
        {
            if ( noteTimer > desiredNoteTimer)
            {
                noteTimer = 0;
                Instantiate(noteParticle,transform.position, Quaternion.identity);
            }
            currentlyDisplayedScore += Time.deltaTime * 100f;
        }
        
        if (currentlyDisplayedScore > success)
        {
            currentlyDisplayedScore = success;
        }

        if ( currentlyDisplayedScore == success && success == successLastFrame && noteTimer > desiredNoteTimer)
        {
                noteTimer = 0;
                Instantiate(noteParticle,transform.position, Quaternion.identity);
        }
        
        jaugeSuccessImage.fillAmount = currentlyDisplayedScore/100f;


        //scoreText.text = ""+Mathf.RoundToInt(currentlyDisplayedScore)+"%";
    }

    void PlayRandomSound(AudioClip[] soundList)
    {
        AudioClip desiredSound = soundList[Random.Range(0,soundList.Length)];
        AudioSource.PlayClipAtPoint(desiredSound, Camera.main.transform.position);
    }


    public void GameOver()
    {
        if (isPlaying)
        {
            if (gameoverSound) AudioSource.PlayClipAtPoint(gameoverSound, Camera.main.transform.position); 
            gameoverScreen.SetActive(true);
            currentAnim = Animation.loose;
            idleTimer = 0;
            isPlaying = false;
            canMove = false;
            MusiqueB.Stop();
            MusiqueC.Stop();
            MusiqueA.Stop();
            //Invoke("RestartGame", 5f);
        }
    }

     public void Victory()
     {
         if (isPlaying)
         {
            if (victorySound) AudioSource.PlayClipAtPoint(victorySound, Camera.main.transform.position); 
            victoryScreen.SetActive(true);
            currentAnim = Animation.victory;
            canMove = false;
            isPlaying = false;
            MusiqueB.Stop();
            MusiqueC.Stop();
            MusiqueA.Stop();
            GameObject.Find("Les_MEGA_Spotlights").GetComponent<LesMegaSpotlightsScript>().ActivateAll();
         }
     }

    public void RestartGame()
    {
        SceneManager.LoadScene(0);
    }


    void AddScore(float amount)
    {
        success += amount;
    }


    void HardDancing(bool isOn)
    {
        if (isOn)
        {
            Debug.Log("Started HardDance");
            hardDancing = true;
        }
        else
        {
            Debug.Log("Stopped HardDance");
            hardDancing = false;
        }
    }



Vector3 oldPlayerPos;
float desiredTomatoTimer = 3f;
    void TomatoLauncher()
    {
        if (hardDancing)
        {
            idleTimer = 0;
            desiredNoteTimer = 0.1f;
        }
        else desiredNoteTimer = 0.5f;


        
        if (idleTimer > desiredTomatoTimer+1f*Random.value)
        {
            desiredTomatoTimer = 1.3f;
            oldPlayerPos = transform.position;
            tomatoLauncher.transform.position = new Vector3(oldPlayerPos.x, 0, -7.45f);
            tomatoLauncher.gameObject.SetActive(true);
            Invoke("TomatoLaunch",1f);
            idleTimer = 0;
        }
    }

    void TomatoLaunch()
    {
        tomatoLauncher.gameObject.SetActive(false);
        if (isPlaying)
        {
            Instantiate(tomate,new Vector3(oldPlayerPos.x,0,-10f), Quaternion.identity);
        }
    }

    void RoseLauncher()
    {
        if (success < 30f && successLastFrame > 30f)
        {
            GameObject thisrose = Instantiate(rose,new Vector3(Random.Range(-7f, 7f),0,-10f), Quaternion.identity);
        }
    }


    void OnTriggerEnter(Collider col)
    {
        if (col.tag == "MegaSpotlight")
        {
            PlayRandomSound(triggerOvation);
        }
    }

    void StartOvation()
    {
        foule.BroadcastMessage("StartOvation", SendMessageOptions.DontRequireReceiver);
    }

    void EndOvation()
    {
        foule.BroadcastMessage("EndOvation", SendMessageOptions.DontRequireReceiver);
    }




} // FIN DU SCRIPT
