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

public class FlameFriend : MonoBehaviour {

	public Vector2 _home; 
	Vector2 stopPoint; 

	private Vector3 mousePos;
	public GameObject chargePrefab;
	public GameObject buddyArea; 
	public int chargesCount = 6; 
	public int chargesOut = 0;
	public float returnTimer = 5f; 

	private bool outState = false;
	private bool b_isMoving = false;
	private bool b_moveActivated = false;

	public float timePointS;
	public float currentTime;


	// Use this for initialization
	void Start () {
		currentTime = timePointS;
	}//end Start
	
	// Update is called once per frame
	void Update () {
		currentTime -= Time.deltaTime;
		if(Input.GetKeyUp(KeyCode.Mouse0)){
			mousePos = Input.mousePosition;
			mousePos = Camera.main.ScreenToWorldPoint (mousePos);
			b_isMoving = true;
			b_moveActivated = true;
			stopPoint = mousePos;
			MoveToClick (stopPoint);
		}
		else if(Input.GetKeyUp(KeyCode.Mouse1)){
			Vector3 mousePos = Input.mousePosition;
			mousePos = Camera.main.ScreenToWorldPoint (mousePos);
			UseCharge(mousePos);
		}
		else if(!outState && returnTimer == 0){
			ReturnHome ();
		}
	}//end Update

	void FixedUpdate(){
		if (b_isMoving && b_moveActivated == true) {
			MoveToClick (stopPoint);
		}
	}

	void UseCharge(Vector3 goToPoint){
		outState = true;
		if(chargesOut <= 3){
			GameObject spawnFlame = GameObject.Instantiate (chargePrefab); //getting object
			spawnFlame.transform.parent = transform.parent;//setting buddy to parent of new object 
			//spawnFlame.GetComponent<ChargeScript>().SetDesination(goToPoint);//
			chargesOut++;
			
		}
		else if(chargesCount == 0){}
	}// end UseCharge

	void MoveToClick(Vector2 goToPoint){
		b_moveActivated = true;
		Vector2 currentPos = gameObject.GetComponent<Transform>().position;
		currentPos = transform.TransformPoint(currentPos);

		//currentTime -= Time.deltaTime; 
		outState = true; 
		Vector2 nextArea = Vector2.Lerp(_home, goToPoint,(timePointS - currentTime) / timePointS); 
		/*nextArea.z = transform.position.z;*/ 
		this.transform.Translate (nextArea * Time.deltaTime);
		if (currentPos == stopPoint) {
			b_isMoving = false;
		}
		Debug.DrawLine (transform.position, stopPoint, Color.red, 5.0f);
	}// end MoveToClick

	void ReturnHome(){

		currentTime -= Time.deltaTime; 
		Vector2 currentArea = transform.position;
		Vector3 nextArea = Vector2.Lerp(currentArea, _home,(timePointS - currentTime) / timePointS); 
		/*nextArea.z = transform.position.z;*/ 
		this.transform.position = nextArea;
	}// end ReturnHome


	public void _removeCharge(){
		chargesOut--;
	}// end _removeCharge

	/*void HomeBase(){
		this.transform.position = buddyArea;  
	}//end HomeBase */
}
