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

public class PlayerHead : MonoBehaviour {

	public Sprite[] HeadDirection;
	public float HeadScaleRatio;
	private SpriteRenderer m_OwnRenderer;
	private Player m_Parent;
	private PlayerGameplay m_ParentGameplay;
	private Animator m_Animator;
	private float HEADSCALE_FACTOR = 0.3f;
	private bool canPlay;
	private const int DEFAULT_HEAD = 6;
	private const float ANGLE_IN_CIRCLE = 360.0f;
	private float pulsateValue;
	private float PULSATE_RATE = 1500.0f;
	public AudioSource splat;

	// Use this for initialization
	void Start () {
		m_Parent = transform.parent.GetComponent<Player>();
		m_ParentGameplay = transform.parent.GetComponent<PlayerGameplay>();
		m_OwnRenderer = gameObject.GetComponent<SpriteRenderer>();
		m_Animator = GetComponent<Animator>();
		m_Animator.enabled=false;
		canPlay = false;
		HeadScaleRatio = 0.0f;
		pulsateValue = 270.0f;
	}
	
	// Update is called once per frame
	void Update () {
		if(m_ParentGameplay.m_IsDead) {
			if(canPlay)
			{
				splat.Play();
				transform.localScale = new Vector3(1.0f+HEADSCALE_FACTOR,1.0f+HEADSCALE_FACTOR,1.0f+HEADSCALE_FACTOR);
				pulsateValue = 270.0f;
				canPlay = false;
				m_Animator.enabled=true;
			}
		
		}
		else
		{
			canPlay = true;
			m_Animator.enabled=false;
			splat.Stop();

			m_OwnRenderer.color = new Color((255.0f-44.0f*HeadScaleRatio)/255, (255.0f-200.0f*HeadScaleRatio)/255, (255.0f-236.0f*HeadScaleRatio)/255);//Color tinting based on head size.

			if(pulsateValue<ANGLE_IN_CIRCLE)
			{
				pulsateValue+=Time.deltaTime*HeadScaleRatio*PULSATE_RATE;
			}
			pulsateValue = pulsateValue % ANGLE_IN_CIRCLE;
			float headScaleWithOffset = 1.0f+(Mathf.Sin(pulsateValue*Mathf.Deg2Rad)+1.0f)*0.5f*HEADSCALE_FACTOR;
			transform.localScale = new Vector3(headScaleWithOffset,headScaleWithOffset,headScaleWithOffset);

			if(m_Parent)
			{
				if(m_Parent.IsMoving)
				{
					m_OwnRenderer.sprite = HeadDirection[m_Parent.PlayerDirection];
				}
				else
				{
					m_OwnRenderer.sprite = HeadDirection[DEFAULT_HEAD];
				}
			}
		}

	}
}
