using UnityEngine;
using System.Collections;

public class PlayerMainController : PlayerController {
	
	public Vector2 summonPos;
	public PlayerSummonController summon;

	public GameObject deathAnim;
	public GameObject castAnim;  
	public GameObject upgradeAnim;  

	private Vector3 spawnPoint;  
	private bool frozen;

	// Use this for initialization
	void Start () { 
		spawnPoint = transform.position; 
		frozen = false;
		facedir = 1;
		GainFocus();
	}
	
	
	public void Respawn(){
		transform.position = spawnPoint;
		rigidBody.velocity = Vector2.zero;
		rigidBody.rotation = 0; 
		frozen = false;
	} 

	// Update is called once per frame
	
	void Update(){
		if (!frozen && (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.UpArrow))){
			Jump(jumpSpeed);
		}  
		WizzardAnimScript.bOnGround = CheckGrounded();
		WizzardAnimScript.velocity = rigidBody.velocity;
	}
	
	// Update is called once per frame
	void FixedUpdate () {   
		rigidBody.velocity = (new Vector2(rigidBody.velocity.x,rigidBody.velocity.y - gravity));
		
		if (!frozen && Input.GetKey(KeyCode.RightArrow)){
			SetHorizontalVelocity(moveSpeed);
			//rigidBody.AddForce(new Vector2(movespeed,rigidBody.velocity.y));
		} 
		
		if (!frozen &&Input.GetKey(KeyCode.LeftArrow)){
			SetHorizontalVelocity(-moveSpeed);
			//rigidBody.AddForce(new Vector2(-movespeed,rigidBody.velocity.y));
		} 

		if (rigidBody.velocity.x>0) facedir = 1;
		if (rigidBody.velocity.x<0) facedir = -1;
	}  
	
	public void SetPlayerFrozen(bool inp){
		frozen  = inp;
		if (inp==true){
			castAnim.GetComponent<ParticleSystem>().emissionRate = 60;
		} else {
			castAnim.GetComponent<ParticleSystem>().emissionRate = 0; 
			//Destroy(castAnimInstance);
		}
	}
	
	public bool IsFrozen(){
		return frozen;
	}

	public void GainFocus(){
		CameraController.SetFollowTarget(this);
		CameraController.SetOffset(new Vector2(0,1));
		CameraController.SetZoom(1.0f);
		DestroyByFall.SetFollowTarget(this);
		WizzardAnimScript.bCasting = false; 
	}

	public override void Kill(){
		summon.Kill();
		Instantiate(deathAnim).transform.position=this.transform.position;
		Respawn ();
	}

	void OnTriggerEnter2D(Collider2D other){
		if (other.gameObject.tag == "CheckPoint"){
			CheckPointController cp = other.gameObject.GetComponent<CheckPointController>();
			if (cp.IsActive()){
				spawnPoint = cp.transform.position;
				cp.Use ();
				Debug.Log("Triggered");
			}
		} 
	}
}
