using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Janus;

[Script(ScriptRole.View)]
public class DinoNestView : MonoBehaviour
{
	DinoNestLogic _logic;
	Animator _animator;
	Animator[] _dinoBabyAnimators;
	ParticleSystem _eggBits;
	int _fryingHash = Animator.StringToHash("Frying");
	int _happyHash = Animator.StringToHash("Happy");
	ParticleSystem[] _babyNoteEmitters;

	void Awake()
	{
		_logic = GetComponent<DinoNestLogic>();
		_animator = GetComponent<Animator>();
		_dinoBabyAnimators = transform.FindChild("dino_babies").GetComponentsInChildren<Animator>();
		_eggBits = transform.FindChild("egg_bits").GetComponent<ParticleSystem>();
		_babyNoteEmitters = transform.GetComponentsInChildren<ParticleSystem>().Where(ps => ps.name == "music_note_emitter").ToArray();
	}

	void OnSpawn ()
	{
		_logic.Frying.EntryPassed += OnFryingChanged;
	}

	void OnFryingChanged(Timeline<bool> timeline, TimelineEntry<bool> entry)
	{
		if (entry.Value)
			StartCoroutine(FryEggAsync());
	}

	/// <summary>
	/// Plays the various animations at certain times. The total duration of this coroutine should ideally add up to
	/// the same time as DinoNestLogic.FryingDuration.
	/// </summary>
	IEnumerator FryEggAsync()
	{
		this.PlayPooledSound("dino_place_egg");
		_animator.SetBool(_fryingHash, true);
		yield return new WaitForSeconds(0.5f);
		for (int i = 0; i < _dinoBabyAnimators.Length; i++)
			_dinoBabyAnimators[i].SetBool(_fryingHash, true);
		this.PlayPooledSound("gekku_burnt");
		yield return new WaitForSeconds(1.2f);
		for (int i = 0; i < _dinoBabyAnimators.Length; i++)
			_dinoBabyAnimators[i].SetBool(_fryingHash, false);
		yield return new WaitForSeconds(0.8f);
		this.PlayPooledSound("sizzle");
		yield return new WaitForSeconds(1f);
		_animator.SetBool(_fryingHash, false);
		_eggBits.Play();
		this.PlayPooledSound("dino_baby_chomp");
		yield return new WaitForSeconds(0.3f);
		this.PlayPooledSound("dino_baby_chorus");
		for (int i = 0; i < _dinoBabyAnimators.Length; i++)
			_dinoBabyAnimators[i].SetBool(_happyHash, true);
		for (int i = 0; i < _babyNoteEmitters.Length; i++)
			_babyNoteEmitters[i].Play();
		yield return new WaitForSeconds(1f);
		for (int i = 0; i < _babyNoteEmitters.Length; i++)
		{
			_babyNoteEmitters[i].Clear();
			_babyNoteEmitters[i].Stop();
		}
		for (int i = 0; i < _dinoBabyAnimators.Length; i++)
			_dinoBabyAnimators[i].SetBool(_happyHash, false);
	}
}