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

public class PizzaMinigameHandler : MonoBehaviour
{
    public static PizzaMinigameHandler Instance;

    [Header("Bridge")]
    [SerializeField] private Transform bridge;
    [SerializeField] private float bridgeScrollSpeed = 1f;

    [Header("Players")]
    [SerializeField] private SimpleCharacter player1;
    [SerializeField] private SimpleCharacter 
        player2,
        player3;

    [Header("Settings")]
    [SerializeField] private int pizzas = 10;
    [SerializeField] private int pizzaPointGain = 500,
        pizzaPointLoss = 150;

    [SerializeField] private MiniGameDone gameDone;
    [SerializeField] private GameObject minigame, canvasObject;

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else if (Instance != this)
        {
            Destroy(this);
        }
    }

    // Update is called once per frame
    void Update ()
    {
        ScrollBridge();
	}

    private void ScrollBridge()
    {
        bridge.transform.Translate(new Vector3(-bridgeScrollSpeed * Time.deltaTime, 0, 0));
    }

    public void SetPlayerVisuals(CharacterRandomizer.Character character1, CharacterRandomizer.Character character2, CharacterRandomizer.Character character3)
    {

        player1.SetHeadSprites(character1);

        player2.SetHeadSprites(character2);

        player3.SetHeadSprites(character3);

    }

    public void StopPlayers()
    {
        List<SimpleCharacter> players = new List<SimpleCharacter>() { player1, player2, player3 };
        foreach(SimpleCharacter player in players)
        {
            player.SetDirection(SimpleCharacter.HeadDirection.Down);
            player.SetSpeed(Vector2.zero, 0f);
        }
    }

    private void FinishMinigame()
    {
        CrowdMinigameManager.Instance.SetState(CrowdMinigameManager.State.Elevator);
    }

    public void WinMinigame()
    {
        Score.Instance.UpdateScore(pizzas * pizzaPointGain);
        minigame.SetActive(false);
        canvasObject.gameObject.SetActive(false);
        StartCoroutine(WinEffect());
    }


    private IEnumerator WinEffect()
    {
        bridgeScrollSpeed = 0;
        gameDone.gameObject.SetActive(true);
        yield return new WaitForSeconds(3f);
        FinishMinigame();
    }


    public void DropPizza()
    {
        if (pizzas < 1)
            return;
        pizzas--;
        Score.Instance.UpdateScore(-pizzaPointLoss);
        if(pizzas <= 0)
        {
            bridgeScrollSpeed = 0;
            minigame.SetActive(false);
            canvasObject.gameObject.SetActive(false);
            FinishMinigame();
        }
    }

}
