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

public class BattleState : State {
	[SerializeField] private StarShipController[] enemies = null; // set from editor
	[SerializeField] private StarShipController player = null; // set from editor
	[SerializeField] private List<ResourceController> resources = new List<ResourceController>();
	private int damage = 1;

	readonly Quaternion playerRotation = Quaternion.identity;
	readonly Quaternion enemyRotation = Quaternion.Euler(0, 0, 180);

	BattleUI battleUI = null;

	protected override void OnStateShow() {
		battleUI = UILayer.Show<BattleUI> ();
		battleUI.HideNext ();
		StartBattle ();
	}

	void StartBattle () {
		StarShipConfig heroConfig = new StarShipConfig(StarShip.Type.hero, 100);
		player = StarShipController.Load (new StarShip(heroConfig), transform, new Vector3(-3, 1), playerRotation);

		enemies = new StarShipController[2];
		StarShipConfig enemyConfig = new StarShipConfig(StarShip.Type.small, 10);
		enemies[0] = StarShipController.Load (new StarShip(enemyConfig), transform, new Vector3(3, -1), enemyRotation, GenerateDrop(transform, enemyConfig));
		StarShipConfig enemy2Config = new StarShipConfig(StarShip.Type.medium, 10);
		enemies[1] = StarShipController.Load (new StarShip(enemy2Config), transform, new Vector3(3, 2), enemyRotation, GenerateDrop(transform, enemy2Config));
	}

	List<ResourceController> GenerateDrop (Transform parent, StarShipConfig config) {
		List<ResourceController> drop = new List<ResourceController> ();
		drop.Add (ResourceController.Load("money", 1, transform, Vector3.zero));
		drop.Add (ResourceController.Load("money", 1, transform, Vector3.zero));
		drop.Add (ResourceController.Load("crystal", 1, transform, Vector3.zero));
		drop.Add (ResourceController.Load("material", 2, transform, Vector3.zero));
		drop.Add (ResourceController.Load("material", 2, transform, Vector3.zero));
		resources.AddRange (drop);
		return drop;
	}

	bool IsAllEnemiesDestroyed () {
		foreach (var enemy in enemies) {
			if (enemy.IsAlive) {
				return false;
			}
		}
		return true;
	}

	void Update () {
		if (Input.GetMouseButtonDown (0)) {
			Ray ray = MainCamera.mainCamera.ScreenPointToRay (Input.mousePosition);

			foreach (var resource in resources) {
				if (resource.IsHit (ray)) {
					resource.Collect (player.transform.position);
				}
			}
			foreach (var enemy in enemies) {
				enemy.Fire (ray, damage);
			}
		}
		if (IsAllEnemiesDestroyed ()) {
			battleUI.ShowNext ();
		}
	}
}
