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

public class ResourceController : MonoBehaviour {

	public enum State {
		Hided,
		Dropped,
		Floating,
		Collected
	}

	[SerializeField]private HitObjectController hitController = null; // Set from editor
	private int count = 0;
	private State state = State.Hided;
	private Vector3 floatVector = Vector3.zero;
	// collect coords
	private Vector3 endPosition = Vector3.zero;
	private Vector3 startPosition = Vector3.zero;
	private float animationTimer = 0;
	private const float collectionTime = 0.5f; // TODO replace on speed and distance
	private const float dropTime = 0.4f; // TODO replace on speed and distance
	private Vector3 rotationAxis;
	private const float rotationSpeed = 60f;

	public void Start() {
		rotationAxis = Random.insideUnitSphere.normalized;
	}

	public void Update() {
		switch (state) {
		case State.Dropped:
			AnimateDrop ();
			break;
		case State.Floating:
			transform.position += floatVector * Time.deltaTime;
			transform.rotation *= Quaternion.AngleAxis (rotationSpeed * Time.deltaTime, rotationAxis);
			break;
		case State.Collected:
			AnimateCollection ();
			break;
		}
	}

	void AnimateDrop () {
		animationTimer -= Time.deltaTime;
		if (animationTimer > 0) {
			float animation = 1f - animationTimer / dropTime;
			transform.position = Vector3.Lerp (endPosition, startPosition, 1f - animation * animation);
		} else {
			state = State.Floating;
		}
	}

	void AnimateCollection () {
		animationTimer -= Time.deltaTime;
		if (animationTimer > 0) {
			float animation = 1f - animationTimer / collectionTime;
			transform.position = Vector3.Lerp (endPosition, startPosition, 1f - animation * animation);
		} else {
			Destroy (gameObject);
		}
	}

	public static ResourceController Load (string name, int count, Transform parent, Vector3 position) {
		var resourcePrefab = Resources.Load<ResourceController> ("Prefabs/Resources/" + name);
		var resourceController = Instantiate<ResourceController>(resourcePrefab, position, Quaternion.identity, parent);
		resourceController.count = count;
		resourceController.state = State.Hided;
		resourceController.gameObject.SetActive (false);
		return resourceController;
	}

	public void Drop (Vector3 position) {
		gameObject.SetActive (true);
		transform.position = position;
		floatVector = Random.insideUnitCircle * 0.3f; //TODO
		state = State.Dropped;
		startPosition = transform.position;
		endPosition = startPosition + floatVector * 4f;
		animationTimer = dropTime;
	}

	public bool IsHit(Ray ray) {
		if (state != State.Floating) {
			return false;
		}
		return hitController.IsHit (ray);
	}

	public void Collect(Vector3 collectPosition) {
		if (state == State.Floating) {
			state = State.Collected;
		}
		startPosition = transform.position;
		endPosition = collectPosition;
		animationTimer = collectionTime;
	}
}
