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

public class OutroManager : MonoBehaviour
{
    public CollectiblesTracker tracker;
    public PlayerControl player;

    public float targetPositionRight = 1f;
    public float targetPositionThreshold = 1f;
    public Transform targetPosition;
    public GameObject scoreBoard;
    public CameraHandler cameraHandler;
    public Animator playerAnimator;
    public Animator otherPlayerAnimator;

    private bool gameCompleted = false;

    private void OnTriggerEnter2D(Collider2D other) {
        if(!gameCompleted) {
            if(other.tag == "Player") {
                // Complete game!
                gameCompleted = true;

                // Stop timer!
                tracker.StopEndGameTimer();

                // Start animation
                StartCoroutine(DoEndGameCinematic());
            }
        }
    }

    private IEnumerator DoEndGameCinematic() {

        // Next: remove player control
        player.enableUserControl = false;
        cameraHandler.enabled = false;

        // Wait a bit (for player to stop moving)
        player.ResetInput();
        yield return new WaitForSeconds(0.5f);

        // Move player to right of us
        float target = player.transform.position.x - transform.position.x - targetPositionRight;
        while(target > targetPositionThreshold || target < -targetPositionThreshold) {
            // We are to much to the right
            player.ResetInput();
            if(target > targetPositionThreshold) {
                player.AutoRunLeft();
            }
            if(target < -targetPositionThreshold) {
                player.AutoRunRight();
            }

            target = player.transform.position.x - transform.position.x - targetPositionRight;
            yield return null;
        }
        player.ResetInput();

        // Ok, we are somewhat in position
        /*float time = Time.timeSinceLevelLoad;
        Vector3 currentPosition = player.transform.position;
        while(Time.timeSinceLevelLoad - time < 0.3f) {
            float percent = (Time.timeSinceLevelLoad - time)/ 0.3f;
            // Interpolate to position
            player.transform.position = currentPosition + (targetPosition.position - currentPosition)*percent;
            yield return null;
        }*/

        // Now, start animations
        player.AutoLookLeft();

        // Animate hug!
        playerAnimator.SetTrigger("PlayEndGame");
        otherPlayerAnimator.SetTrigger("PlayEndGame");

        yield return new WaitForSeconds(10f);

        // Show score board
        scoreBoard.SetActive(true);

        yield return new WaitForSeconds(5f);

        // Re-enable controls
        player.enableUserControl = true;
        cameraHandler.enabled = true;
    }
}
