﻿using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {

	public GameObject candyPrefab;
	public Transform launchPoint;


	public GameObject launchObj;

	public bool launching;

	int shotsLeft = 10;

	int score = 0;

	public UILabel scoreLabel;
	public UILabel shotsLeftLabel;

	// Use this for initialization
	void Start () {
		UpdateScore();
	}

	public void HitEnemy()
	{
		score += 10;
		UpdateScore();
	}
	
	// Update is called once per frame
	void Update () {
		if( Input.GetMouseButtonDown(0) && shotsLeft > 0 )
		{
			launching = true;
			 
			launchObj = (GameObject)GameObject.Instantiate( candyPrefab, launchPoint.transform.position, Quaternion.identity );

			Rigidbody2D rb = launchObj.GetComponent<Rigidbody2D>();
			//rb.velocity = targetDir * 10;
			rb.isKinematic = true;

			shotsLeft--;
			UpdateScore();

		}


		if(launching && Input.GetMouseButtonUp( 0 ))
		{
			launching = false;
		

			Vector3 mousePos = Input.mousePosition;
			Vector3 targetPos = Camera.main.ScreenToWorldPoint( new Vector3(mousePos.x, mousePos.y, 10));

			Vector3 targetDir = targetPos - launchPoint.position;

			targetDir.Normalize();


			Rigidbody2D rb = launchObj.GetComponent<Rigidbody2D>();
			rb.isKinematic = false;

			rb.velocity = targetDir * 10;

			GameObject.Destroy( launchObj, 10.0f);


		}



	}

	public void UpdateScore()
	{
		scoreLabel.text = "Score: "+score;	

		shotsLeftLabel.text = "Shots Left: "+shotsLeft;
	}
}
