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

/// <summary>
/// Crowd behaviour.
/// </summary>
public class CrowdBehaviour : MonoBehaviour {
	/// <summary>
	/// The on add.
	/// </summary>
	public System.Action OnAdd;
	/// <summary>
	/// The on remove.
	/// </summary>
	public System.Action OnRemove;
	/// <summary>
	/// The player.
	/// </summary>
	private GameObject player;
	/// <summary>
	/// The cfg radius minimum.
	/// </summary>
	[SerializeField]
	private float cfgRadiusMin = 0.5f;
	/// <summary>
	/// The cfg radius max.
	/// </summary>
	[SerializeField]
	private float cfgRadiusMax = 3f;
	/// <summary>
	/// The cfg velocity max.
	/// </summary>
	[SerializeField]
	private float cfgVelocityMax = 0.3f;
	/// <summary>
	/// The cfg radius shrink.
	/// </summary>
	[SerializeField]
	private float cfgRadiusShrink = 0.05f;
	/// <summary>
	/// The cfg key code for radius.
	/// </summary>
	[SerializeField]
	private KeyCode cfgKeyCodeForRadius = KeyCode.Space;
	/// <summary>
	/// The current radius.
	/// </summary>
	private float currentRadius;
	/// <summary>
	/// The current velocity.
	/// </summary>
	private float currentVelocity;

	/// <summary>
	/// Start this instance.
	/// </summary>
	void Start () {
		player = GameObject.Find ("Player");
		currentRadius = cfgRadiusMax;
		currentVelocity = cfgVelocityMax;
	}
	
	/// <summary>
	/// Update this instance. Update is called once per frame
	/// </summary>
	void Update () {
		var newPosition = player.transform.position;
		newPosition.y = transform.position.y;
		transform.position = Vector3.MoveTowards(transform.position, newPosition, currentVelocity);

        if (Input.GetKey(cfgKeyCodeForRadius))
        {
			Radius -= cfgRadiusShrink;
		} else {
			Radius += cfgRadiusShrink;
		}
	}
	/// <summary>
	/// Adds the follower.
	/// </summary>
	/// <param name="follower">Follower.</param>
	public void AddFollower(GameObject follower) {
		follower.transform.parent = gameObject.transform;
		FireAddEvent();
	}
	/// <summary>
	/// Removes the follower.
	/// </summary>
	/// <param name="follower">Follower.</param>
	public void RemoveFollower(GameObject follower) {
		follower.transform.parent = null;
		FireRemoveEvent();
	}
	/// <summary>
	/// Gets the radius.
	/// </summary>
	/// <value>The radius.</value>
	public float Radius {
		get {
			return currentRadius;
		}
		private set {
			if(value >= cfgRadiusMin && value <= cfgRadiusMax) {
				currentRadius = value;
				currentVelocity = cfgVelocityMax * (value / cfgRadiusMax);
			}
		}
	}

	/// <summary>
	/// Fires the add event.
	/// </summary>
	private void FireAddEvent()
	{
		if (OnAdd != null) {
			OnAdd();
		}
	}
	/// <summary>
	/// Fires the remove event.
	/// </summary>
	private void FireRemoveEvent()
	{
		if (OnRemove != null) {
			OnRemove();
		}
	}
}
