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

public class AdventureState : State {
	[SerializeField] private ShipMarkerController heroShipMarker = null;
	[SerializeField] private SystemObjectController adventurePointPrototype = null; // Set from editor
	[SerializeField] private SystemObjectController[] systemObjects = null;
	[SerializeField] private ExplorePointConfig[] points = null;

	void Start() {
		points = GenerateLevel ();
		systemObjects = GenerateMap (points);
		heroShipMarker.SetPosition (Quaternion.Euler(0, 0, Random.Range(0, 360f)) * new Vector3(3, 0));
	}

	protected override void OnStateShow () {
		UILayer.Show<MapUI> ();
	}

	ExplorePointConfig[] GenerateLevel () {
		List<ExplorePointConfig> points = new List<ExplorePointConfig> ();
		int planetCount = Random.Range (3, 6);
		for (int i = 0; i < planetCount; i++) {
			var point = new ExplorePointConfig (i * 0.6f, i * 105f + Random.Range(-20f, 20f), BattleActivityConfig.GenerateRandom ());
			points.Add (point);
		}
		return points.ToArray ();
	}

	SystemObjectController[] GenerateMap (ExplorePointConfig[] pointsData) {
		List<SystemObjectController> points = new List<SystemObjectController> ();
		foreach (var pointData in pointsData) {
			points.Add (GeneratePoint (pointData));
		}
		adventurePointPrototype.gameObject.SetActive (false);
		return points.ToArray ();
	}

	SystemObjectController GeneratePoint (ExplorePointConfig systemData) {
		var systemObject = Instantiate<SystemObjectController> (adventurePointPrototype, transform);
		systemObject.Init (systemData);
		return systemObject;
	}

	void MoveToPoint (ExplorePointConfig systemObject) {
		heroShipMarker.SetPosition (systemObject.GetPosition(), 0.2f);
		State.Show<ShipFlyState> ();
	}

	void Update () {
		if (Input.GetMouseButtonDown (0)) {
			Ray ray = MainCamera.mainCamera.ScreenPointToRay (Input.mousePosition);
			foreach (var point in systemObjects) {
				if (point.IsHit (ray)) {
					MoveToPoint (point.Config);
				}
			}
		}
	}
}
