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

public class ARitizeEditor : MonoBehaviour {


	[MenuItem("NexTech/Learning Steps/Create Label")]
	public static void CreateLearningStepsLabel()
	{
		if(Selection.objects.Length == 0)
		{
			Debug.LogError("No GameObject selected in scene -- select object you want a label for!");
			return;
		}
		List<GameObject> newObjects = new List<GameObject>();
		foreach (Object o in Selection.objects)
		{
			GameObject selectedGO = o as GameObject;
			if(selectedGO == null)
			{
				Debug.LogError("No GameObject selected in scene -- select object you want a label for!");
				return;
			}
			GameObject newLabelGO = CreateChild(selectedGO);
			newLabelGO.name = string.Format("[LABEL]{0}", selectedGO.name);
			GameObject newLabelPositionAnchorGO = CreateChild(newLabelGO);
			newLabelPositionAnchorGO.name = "[LABEL POSITION]";
			newObjects.Add(newLabelPositionAnchorGO);

			MeshFilter selectedObjectMeshFilter = selectedGO.GetComponent<MeshFilter>();
			if(selectedObjectMeshFilter != null)
			{
				selectedGO.AddComponent(typeof(MeshCollider));
			}
			else
			{
				Debug.Log(string.Format("{0} doesn't have a mesh so you won't be able to tap on it", selectedGO.name));
			}
		}
		Selection.objects = newObjects.ToArray();
	}

	// [MenuItem("NexTech/Dev/DeleteDS")]
	// public static void DeleteDS()
	// {
	// 	string subfolderRoot = "./";
	// 	string[] files = Directory.GetFiles(subfolderRoot, "*.DS_Store", SearchOption.AllDirectories);

	// 	for(int i = 0; i < files.Length; i++)
	// 	{
	// 		Debug.Log(files[i]);
	// 		File.Delete(files[i]);
	// 	}
	// }

	public static GameObject CreateChild(GameObject parent)
	{
		GameObject newGO = new GameObject();
		newGO.transform.parent = parent.transform;
		newGO.transform.localPosition = Vector3.zero;
		return newGO;
	}

	[MenuItem("NexTech/Learning Steps/Create Animation Controller")]
	public static void CreateLearningStepsAnimator()
	{
		Debug.Log("Create Animation Controller");

		//get list of current selected assets
		List<string> selectedObjectPaths = new List<string>();
		foreach (Object o in Selection.objects)
		{
			string assetPath = AssetDatabase.GetAssetPath(o);
			if(!assetPath.Contains(".anim"))
			{
				Debug.LogError("Non animation asset selected! Only select animations!");
				return;
			}
			selectedObjectPaths.Add(AssetDatabase.GetAssetPath(o));
		}

		selectedObjectPaths.Sort();

		string workingDirectory = Directory.GetParent(selectedObjectPaths[0]).ToString();
		UnityEditor.Animations.AnimatorController newAnimator = new UnityEditor.Animations.AnimatorController();
		newAnimator.AddLayer("Base Layer");
		newAnimator.AddParameter("CurrentStep", AnimatorControllerParameterType.Int);
		newAnimator.AddParameter("Replay", AnimatorControllerParameterType.Trigger);
		var stateMachine = newAnimator.layers[0].stateMachine;

		//add states
		List<UnityEditor.Animations.AnimatorState> animatorStates = new List<UnityEditor.Animations.AnimatorState>();
		List<UnityEditor.Animations.AnimatorState> animatorReverseStates = new List<UnityEditor.Animations.AnimatorState>();
		for(int i = 0; i < selectedObjectPaths.Count; i++)
		{
			//find name of animation for this state
			string animationName = Path.GetFileName(selectedObjectPaths[i]).Replace(".anim", "");
			//create state
			var newState = stateMachine.AddState(animationName);
			//add corresponding motion
			newState.motion = AssetDatabase.LoadAssetAtPath(selectedObjectPaths[i], typeof(AnimationClip)) as Motion;
			//add to list so we can do transitions next
			animatorStates.Add(newState);

			//add reverse state
			newState = stateMachine.AddState(animationName + "_R");
			//add corresponding motion
			newState.motion = AssetDatabase.LoadAssetAtPath(selectedObjectPaths[i], typeof(AnimationClip)) as Motion;
			newState.speed = -1f;
			//add to list so we can do transitions next
			animatorReverseStates.Add(newState);
		}

		//add transitions
		for(int i = 0; i < animatorStates.Count; i++)
		{
			//forward transitions
			if(i < animatorStates.Count - 1)
			{
				var newTransition = animatorStates[i].AddTransition (animatorStates[i + 1]);
				SetupTransition(newTransition, i + 1);

				//replay from reverse
				if(i < animatorStates.Count - 1)
				{
					newTransition = animatorReverseStates[i + 1].AddTransition (animatorStates[i]);
					newTransition.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "Replay");
					newTransition.hasExitTime = false;
					newTransition.duration = 0f;
					// SetupTransition(newTransition, i - 1);
				}
			}

			//reverse transitions
			if(i > 0)
			{
				//reverse 
				var newTransition = animatorStates[i].AddTransition (animatorReverseStates[i]);
				SetupTransition(newTransition, i - 1);

				//forward from reverse
				newTransition = animatorReverseStates[i].AddTransition (animatorStates[i]);
				SetupTransition(newTransition, i);

				//reverse from reverse
				if(i < animatorStates.Count - 1)
				{
					newTransition = animatorReverseStates[i + 1].AddTransition (animatorReverseStates[i]);
					SetupTransition(newTransition, i - 1);
				}

				
			}
			
		}

        AssetDatabase.CreateAsset(newAnimator, workingDirectory + "/StepsAnimator.controller");

	}

	public static void SetupTransition(UnityEditor.Animations.AnimatorStateTransition transition, int step)
	{
		transition.AddCondition(UnityEditor.Animations.AnimatorConditionMode.Equals, step, "CurrentStep");
		transition.hasExitTime = false;
		transition.duration = 0f;
	}
}
