using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class BuildController : MonoBehaviour {
	public bool Building = true;
	public GameObject[] BuildableComponents;
	public int CurrentPart = 0;
	public int NumParts = 7;
	public GameObject[] PartsList;

	public GameObject BuildUI;
	public Transform ItemPanel;
	public GameObject ItemPanelItem;

	public AudioSource MusicAudioSource;
	public AudioClip Music;

	public AudioSource BuildAudioSource;
	public AudioClip[] AudioClips;
	
	Transform player;

	void Start () {
		player = GameObject.FindWithTag("Player").transform;
		GeneratePartList ();

		SpawnPart ();
	}

	void GeneratePartList()
	{
		PartsList = new GameObject[NumParts];
		for (int i = 0; i < NumParts; i++) {
			PartsList[i] = BuildableComponents[Random.Range(0, BuildableComponents.Length)];
			GameObject g = Instantiate(ItemPanelItem) as GameObject;
			g.transform.SetParent(ItemPanel);
			g.GetComponent<Image>().sprite = PartsList[i].GetComponent<BaseShipComponent>().Icon;
		}
	}

	void SpawnPart()
	{
		if (CurrentPart < NumParts) {
				GameObject g = Instantiate (PartsList [CurrentPart++]) as GameObject;
				g.AddComponent<RotateAroundShip> ().center = player.position;
				g.AddComponent<Attachable> ().OnAttached = () => 
					{ 
						Destroy(ItemPanel.GetChild(0).gameObject);
						BuildAudioSource.PlayOneShot(AudioClips[Random.Range(0, AudioClips.Length)]);
						SpawnPart ();
					};
		} else {
			EndBuild();
		}
	}

	void EndBuild()
	{
		BuildUI.SetActive (false);
		Building = false;

		MusicAudioSource.clip = Music;
		MusicAudioSource.Play();
	}
}
