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

[RequireComponent(typeof(ParallaxScroller))]
public class Goal : MonoBehaviour
{
	private Player player;

	private ParallaxSpawner spawner;

	private ParallaxScroller scroller;

	[SerializeField] private BGM music;
	private void OnEnable() {
		player = FindObjectOfType<Player>();
		spawner = FindObjectOfType<ParallaxSpawner>();
		scroller = GetComponent<ParallaxScroller>();
		scroller.enabled = false;

		float camHalfWidth = Camera.main.orthographicSize * Screen.width / (float)Screen.height;
		float camXPos = Camera.main.transform.position.x;
		transform.position = new Vector3(camXPos+camHalfWidth+scroller.calcWidth(), 0, 0);
	}

	public void OnTriggerEnter2D(Collider2D other) {
		if(other.GetComponent<Player>()!=null) {
			StartCoroutine("onWin");
		}
	}

	private IEnumerator onWin() {
		if(player.sounds!=null)
			player.sounds.play("win");

		music.FadeOut(4);

		Time.timeScale = 0f;

		var fade = Camera.main.GetComponent<ScreenTransitionImageEffect>();
		while(fade.maskValue<1f) {
			yield return new WaitForSecondsRealtime(1f/30f);
			fade.maskValue += 1f/30f / 5f;
		}
		
		yield return new WaitForSecondsRealtime(1f);
		Time.timeScale = 1f;
		Scene scene = SceneManager.GetActiveScene();
		SceneManager.LoadScene(scene.name);
	}

    void Update() {
        if(player.GetProgress() > 0.999f) {
			scroller.enabled = true;
			spawner.enabled = false;
		}
    }
}
