﻿using UnityEngine;
using System;
using System.IO;
using System.Collections.Generic;
using Hover.Board.Items;
using Configurator.Utils;

namespace Configurator.Menu.Open
{
	public class OpenMenu : MonoBehaviour
	{
		public bool Enabled {
			get { 
				return hoverboardPanel.GetPanel ().IsEnabled; 
			}
			set {
				if (value) {
					startFileIndex = 0;

					RefreshFiles ();
					RefreshLines ();
				}

				hoverboardPanel.GetPanel ().IsVisible = value;
				hoverboardPanel.GetPanel ().IsEnabled = value; 
			}
		}

		private HoverboardPanel hoverboardPanel;

		private LineSelector[] lineSelectors;

		private ButtonSelector nextButton;

		private ButtonSelector previousButton;

		private string[] files;

		private int startFileIndex;

		private void Awake ()
		{
			hoverboardPanel = GetComponent<HoverboardPanel> ();
			lineSelectors = GetComponentsInChildren<LineSelector> ();

			foreach (var button in GetComponentsInChildren<ButtonSelector>()) {
				if (button.ButtonType == ButtonSelector.Type.Next) {
					nextButton = button;
				} else if (button.ButtonType == ButtonSelector.Type.Previous) {
					previousButton = button;
				}
			}
		}

		private void RefreshFiles ()
		{
			files = Directory.GetFiles (ConfigurationUtils.SaveDirectory);
			Array.Reverse (files);
		}

		private void RefreshLines ()
		{
			for (int lineIndex = 0; lineIndex < lineSelectors.Length; lineIndex++) {
				int fileIndex = startFileIndex + lineIndex;

				if (fileIndex < files.Length) {
					lineSelectors [lineIndex].Label = "Save " + (files.Length - fileIndex);
					lineSelectors [lineIndex].File = files [fileIndex];
					lineSelectors [lineIndex].Enabled = true;
				} else {
					lineSelectors [lineIndex].Label = "";
					lineSelectors [lineIndex].File = "";
					lineSelectors [lineIndex].Enabled = false;
				}
			}

			nextButton.Enabled = (files.Length > lineSelectors.Length);
			previousButton.Enabled = (startFileIndex > 0);
		}

		public void HandleNext ()
		{
			startFileIndex += lineSelectors.Length;
			RefreshLines ();
		}

		public void HandlePrevious ()
		{
			startFileIndex -= lineSelectors.Length;
			RefreshLines ();
		}

		public void HandleCancel ()
		{
			Enabled = false;
		}
	}
}
