﻿using UnityEngine;
using System.Collections;

public class BadGuyManager : MonoBehaviour {

	public GameObject pizzaMakerManager;
	public GameObject badGuyContainer;
	
	public GameObject scoreManager;
	
	public GameObject playerLocation;
	
	private int badGuyLimit = 0;
	private int badGuyCount = 0;


	public Transform[] spawnPoints;

	private float spawnLineDist;

	// Use this for initialization
	void Start () {
	
		
		badGuyLimit = 1;
		badGuyCount = 0;
	}
	
	// Update is called once per frame
	void Update () {
	
		if (badGuyCount < badGuyLimit)
			MakeNewBadGuy();
	
	
		int total = scoreManager.GetComponent<ScoreManager>().modKilled(0);

		if (total > 3)
			badGuyLimit = 2;
		if (total > 9)
			badGuyLimit = 3;
		if (total > 16)
			badGuyLimit = 4;
		
			
	}
	
	
	public void damage(GameObject selectedBadGuy, float pizzaValue, int[] layerOn)	
	{
		BadGuy bg = selectedBadGuy.GetComponent<BadGuy>();

		float damage = pizzaValue;
		
		PizzaSpeciality ps = new PizzaSpeciality(layerOn);
		
		string special = ps.CheckSpeciality();
		if (special != "")
		{
			Debug.Log ("Determine Speciality Effect: " + special);
	
			if (special == bg.getWeakness())
				damage = 20;
		}
		
		
		
		
		
		bg.health -= damage;	

		float newHealthScale = bg.health / bg.healthMax;
		Vector3 h = new Vector3(newHealthScale, 1.0f, 1.0f);
		
		Debug.Log ("Healthbar: " + pizzaValue + ":" + bg.health + ":" + h);

		bg.healthcontainer.transform.localScale = h;

		if (bg.health <= 0.0f)
		{
			kill (selectedBadGuy);
		}	
	}
	
	public void kill(GameObject toKill)
	{
		toKill.GetComponent<BadGuy>().die();
		scoreManager.GetComponent<ScoreManager>().modKilled(1);		
		badGuyCount--;
		
		pizzaMakerManager.GetComponent<PizzaMakerManager>().setCurrentBadGuy(null);
		
	}
	
	private void MakeNewBadGuy()
	{
		Debug.Log ("MakeNewBadGuy()");
		badGuyCount++;
		
		GameObject go = (GameObject)Instantiate(Resources.Load("Prefab/BadGuy"));
		go.transform.SetParent (badGuyContainer.transform);
		
		int r = Random.Range(0, spawnPoints.Length);
		
		go.transform.position = spawnPoints[r].position;
		
		BadGuy bg = go.GetComponent<BadGuy>();
		bg.target = playerLocation;
		bg.pizzaMakerManager = pizzaMakerManager.GetComponent<PizzaMakerManager>();
		//bg.scoreManager = pizzaMakerManager.GetComponent<PizzaMakerManager>().scoreManager;
		bg.badGuyManager = this;
		bg.speed = Random.Range (1f, 1 + (badGuyLimit / 4));
		
		int weakness = Random.Range(0,5);
		if (weakness == 0)
			bg.setWeakness("CHEESE");
		else if (weakness == 1)
			bg.setWeakness("PEPPERONI");
		else if (weakness == 2)
			bg.setWeakness("HAWAIIAN");
		else if (weakness == 3)
			bg.setWeakness("SUPREME");
		else if (weakness == 4)
			bg.setWeakness("VEGGIE");
		else
			bg.setWeakness("");
		
		
	}
	
}
