using UnityEngine;
using System.Collections;

// for battle control
public class BattleState : SpaceStateController
{
	static BattleState instance = null;

	[SerializeField]StarShip hero = null;
	[SerializeField]StarShip enemy = null;

	bool isBattle = false;

	public static void StartBattle()
	{
		BaseUI.AsyncShowWithLoaderUI<BattleUI, LoaderUI>(0, () => {
			Game.SetGameState(4);
			instance.Init();
		});
	}

	public override void OnStateShow (bool fromBigger)
	{
		CameraController.SetPosition(Vector3.zero, false);
		CameraController.SetNeedDistance (7f);
		CameraController.SetBorders (minCameraDistance + 1, minCameraDistance, maxCameraDistance, cameraMinYAngle, cameraMaxYAngle);
	}

	void Init ()
	{
		if(hero != null)
		{
			Destroy (hero.gameObject);
		}
		hero = Utils.LoadPrefab<StarShip>("Prefabs/Ships/ship_4", new Vector3(-3f, 0, -5), transform);
		hero.AttachWeapons(new Weapon[4] {
			Utils.LoadPrefab<Weapon>("Prefabs/Weapons/Plasma"),
			Utils.LoadPrefab<Weapon>("Prefabs/Weapons/Laser"),
			Utils.LoadPrefab<Weapon>("Prefabs/Weapons/DoublePlasma"),
			Utils.LoadPrefab<Weapon>("Prefabs/Weapons/Plasma")
		});
		if(enemy != null)
		{
			Destroy (enemy.gameObject);
		}
		int enemyTurretCount = Random.Range(2, 4);
		enemy = Utils.LoadPrefab<StarShip>("Prefabs/Ships/ship_" + enemyTurretCount.ToString(), new Vector3(3f, 0, 5), transform);
		enemy.transform.localEulerAngles = new Vector3(0, 180, 0);
		Weapon[] weapons = new Weapon[enemyTurretCount];
		string [] weapon_types = {
			"Plasma",
			"Laser",
			"DoublePlasma"
		};
		for(int i = 0; i < weapons.Length; i++)
		{
			weapons[i] = Utils.LoadPrefab<Weapon>("Prefabs/Weapons/" + weapon_types[Random.Range(0, 3)]);
		}
		enemy.AttachWeapons(weapons);
		enemy.gameObject.AddComponent<StarShipAI>();
		enemy.enemy = hero;
		hero.enemy = enemy;

		BattleUI.SetShip(hero, enemy);
		isBattle = true;
	}

	void Awake () {
		instance = this;
	}

	void Update () {
		if (isBattle)
		{
			if (hero.hitPoints <= 0)
			{	// hero lose
				BaseUI.AsyncShowWithLoaderUI<LoseUI, LoaderUI>();
				isBattle = false;
			}
			if (enemy.hitPoints <= 0)
			{	// hero lose
				BaseUI.AsyncShowWithLoaderUI<BattleResultUI, LoaderUI>();
				isBattle = false;
			}
		}
	}
}
