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

/// <summary>
/// Chest Class
/// 
/// Zethzer
/// 
/// Important : watch video 112 for animation and sound, 113 for particle effect to open (9 min)
/// Open the chest, loot and stay open.
/// </summary>

/* For later
[RequireComponent (typeof(BoxCollider))]
[RequireComponent (typeof(AudioSource))] */

public class Chest : MonoBehaviour {
	public enum State {
		Open,
		Close
	}

	private State state;								// our current state
	private Color defaultColor;							// the default color of the chest
	private float maxDistance = 15;						// the max distance the player can be to open the chest
	private bool chestOpen = false;						// boolean for highlighting

	public GameObject mesh;								// the mesh for the renderer
	private Animator animator;							// the controller of the animation

	public List<Item> lootItems = new List<Item>();			// the list of items in the chest
	private bool isUsed = false;

	// Use this for initialization
	void Start () {
		state = State.Close;
		defaultColor = mesh.renderer.material.GetColor("_Color");
		animator = GetComponent <Animator>();
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	public void OnMouseEnter() {
		Highlight(true);
	}

	public void OnMouseExit() {
		Highlight(false);
	}

	/// <summary>
	/// Raises the mouse click event.
	/// </summary>
	public void OnMouseUp() {
		GameObject playerTemp = GameObject.Find("PlayerCharacter");

		// if the player is not find
		if(playerTemp == null) {
			Debug.LogWarning("Can't find the player");
			return;
		}

		// if the player is in distance for open the chest
		if(Vector3.Distance(this.transform.position, playerTemp.transform.position) > maxDistance) {
			return;
		}

		if(state == State.Close && !chestOpen)
			open();
	}

	/// <summary>
	/// Open the chest.
	/// </summary>
	public void open() {
		Loot.chest = this;

		if(!isUsed)
			Populate(Random.Range(2,7));

		animator.SetBool("isOpen", true);

		chestOpen = true;
		state = State.Open;

		Messenger.Broadcast("EjectLoot");
		isUsed = true;
	}

	public void Highlight(bool glow) {
		if(glow && !chestOpen)
			mesh.renderer.material.SetColor("_Color", defaultColor * 1.2f);
		else
			mesh.renderer.material.SetColor("_Color", defaultColor);
	}

	private void Populate(int x) {
		for(int i = 0; i < x; ++i) {
			lootItems.Add(ItemGenerator.CreateItem());
		}
	}
}
