﻿#if UNITY_EDITOR

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

namespace AC.Downloads.ChatLogUI
{

	public class ChatLogTemplate : Template
	{

		#region Variables

		[SerializeField] private GameObject chatLogPrefab = null;
		private const string EventName = "Spawn ChatLog";

		#endregion


		#region PublicFunctions

		public override bool CanInstall (ref string errorText)
		{
			if (KickStarter.settingsManager == null)
			{
				errorText = "No Settings Manager assigned";
				return false;
			}

			if (chatLogPrefab == null)
			{
				errorText = "No prefab assigned";
				return false;
			}

			return true;
		}

		#endregion


		#region ProtectedFunctions

		protected override void MakeChanges (string installPath, bool canDeleteOldAssets, System.Action onComplete, System.Action<string> onFail)
		{
			Undo.RecordObjects (new UnityEngine.Object[] { KickStarter.settingsManager }, "");

			// ChatLog Prefab
			GameObject newPrefab = CopyAsset<GameObject> (installPath, chatLogPrefab, ".prefab");
			if (newPrefab == null)
			{
				onFail.Invoke ("Prefab copy failed.");
				return;
			}
			EditorUtility.SetDirty (newPrefab);

			ActionListAsset spawnChatLogActionList = CreateActionList ("Spawn ChatLog", installPath, newPrefab);

			EventBeginGame newEvent = new EventBeginGame (KickStarter.settingsManager.GetNextAvailableEventID (), EventName, spawnChatLogActionList, new int[0]);
			KickStarter.settingsManager.events.Add (newEvent);

			EditorUtility.SetDirty (KickStarter.settingsManager);

			if (KickStarter.menuManager)
			{
				Menu subtitlesMenu = KickStarter.menuManager.GetMenuWithName ("Subtitles");
				if (subtitlesMenu != null) subtitlesMenu.isLocked = true;

				Menu conversationMenu = KickStarter.menuManager.GetMenuWithName ("Conversation");
				if (conversationMenu != null) conversationMenu.isLocked = true;
			}

			onComplete.Invoke ();
		}

		#endregion


		#region PrivateFunctions
		
		private ActionListAsset CreateActionList (string assetName, string installPath, GameObject newChatLog)
		{
			List<Action> actions = new List<Action>
			{
				ActionInstantiate.CreateNew_Add (newChatLog),
			};

			ActionListAsset newAsset = ActionListAsset.CreateFromActions (assetName, installPath, actions, ActionListType.RunInBackground);
			return newAsset;
		}

		#endregion


		#region GetSet

		public override string Label { get { return "Chat Log"; }}
		public override string PreviewText { get { return "Adds a chat log to the side of the screen, which displays all dialogue text, and optionally Conversation options."; }}
		public override Type[] AffectedManagerTypes { get { return new Type[] { typeof (SettingsManager), typeof (MenuManager) }; }}
		public override bool RequiresInstallPath { get { return true; }}
		public override string FolderName { get { return "Chat Log"; }}

		#endregion

	}


	[CustomEditor (typeof (ChatLogTemplate))]
	public class ChatLogTemplateEditor : TemplateEditor
	{}

}

#endif