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

#if UNITY_EDITOR
public class DialogueSceneMakerWindow : EditorWindow
{
    [SerializeField]
    public List<Dialogue> dialogues = new List<Dialogue>();

    private string characterName;
    private string dialogueText;
    private CharacterExpression expression = CharacterExpression.DEFAULT;

    Vector2 dialoguesScroll;
    private int loadFromDialoguesIndex = 0;

    Rect dialogueAdderWindowRect = new Rect(0, 0, 400, 400);
    Rect dialogueSceneMakerWindowRect = new Rect(400, 0, 400, 600);

    DialogueScene dialogueScene = null;

    string newDialogueSceneName = "";

	List<bool> dialogueFoldouts = new List<bool>();

    [MenuItem ("Tools/DialogueSceneMaker")]
    static void Init()
    {
        DialogueSceneMakerWindow window = (DialogueSceneMakerWindow)EditorWindow.GetWindow(typeof(DialogueSceneMakerWindow));
        window.minSize = new Vector2(800, 400);
		foreach (var character in Resources.LoadAll<CharacterResource>("BS_DialogueSystem/CharacterResources"))
		{
			try
			{
				CharacterResourceEditorWindow.characters.Add(character.characterID, character);
			}
			catch
			{
				Debug.LogError("Character ID is not unique! Check " +
					CharacterResourceEditorWindow.characters[character.characterID].characterName + " and " +
					character.characterName + "!");
				throw;
			}
		}
		window.Show();
    }

    private void OnGUI()
    {
        BeginWindows();
        dialogueAdderWindowRect = GUILayout.Window(1, dialogueAdderWindowRect, DialogueAdderWindow, "Dialogue Adder");
        dialogueSceneMakerWindowRect = GUILayout.Window(2, dialogueSceneMakerWindowRect, DialogueSceneWindow, "Dialogue Scene Maker");
        EndWindows();
    }

    void DialogueAdderWindow(int id)
    {
		/*
        characterName = EditorGUILayout.TextField("Character Name", characterName, GUILayout.MaxWidth(position.width / 2));
		expression = (CharacterExpression)EditorGUILayout.EnumPopup(expression);
        GUILayout.Label("Dialogue");

        dialogueText = EditorGUILayout.TextArea(dialogueText, GUILayout.Height(200), GUILayout.MaxWidth(position.width / 2));

        if (GUILayout.Button("Add new Dialogue", GUILayout.MaxWidth(position.width / 2)))
        {
            AddNewDialogue(new Dialogue(characterName, dialogueText, expression));
            characterName = "";
            dialogueText = "";
			expression = CharacterExpression.DEFAULT;
		}

        EditorGUILayout.BeginHorizontal();
        loadFromDialoguesIndex = EditorGUILayout.IntField(loadFromDialoguesIndex, GUILayout.MaxWidth(position.width / 4));
        if (GUILayout.Button("Add new Dialogue at", GUILayout.MaxWidth(position.width / 4)))
        {
			AddNewDialogue(new Dialogue(characterName, dialogueText, expression));
			characterName = "";
            dialogueText = "";
			expression = CharacterExpression.DEFAULT;
        }
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        loadFromDialoguesIndex = EditorGUILayout.IntField(loadFromDialoguesIndex, GUILayout.MaxWidth(position.width / 4));
        if (GUILayout.Button("Edit Dialogue at", GUILayout.MaxWidth(position.width / 4)))
        {

		}
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        loadFromDialoguesIndex = EditorGUILayout.IntField(loadFromDialoguesIndex, GUILayout.MaxWidth(position.width / 4));
        if (GUILayout.Button("Load from current Dialogues", GUILayout.MaxWidth(position.width / 4)))
        {

        }
        EditorGUILayout.EndHorizontal();
		*/
        GUI.DragWindow();
    }

    void DialogueSceneWindow(int id)
    {
        GUILayout.Label("Current dialogue list", EditorStyles.boldLabel);

		SaveLoadGUI();
		SaveAsNewGUI();
		DialoguesGUI();
		
        GUI.DragWindow();
    }

	#region DialogueSceneWindow Utilities

	private void SaveLoadGUI()
	{
		GUILayout.BeginHorizontal();
		dialogueScene = EditorGUILayout.ObjectField(dialogueScene, typeof(DialogueScene), false) as DialogueScene;
		/*
		GUI.enabled = dialogueScene != null;
		if (GUILayout.Button("Save", GUILayout.Width(100)))
		{
			Save();
		}
		if (GUILayout.Button("Load", GUILayout.Width(100)))
		{
			Load();
		}
		
		GUI.enabled = true;
		*/
		if (dialogueScene != null)
			Load();
		GUILayout.EndHorizontal();
	}

	private void Save()
	{
		dialogueScene.dialogues = dialogues;
	}

	private void Load()
	{
		dialogues = new List<Dialogue>(dialogueScene.dialogues);
		dialogueFoldouts = new List<bool>();
		for (int i = 0; i < dialogues.Count; i++)
		{
			dialogueFoldouts.Add(true);
		}
	}

	private void SaveAsNewGUI()
	{
		GUILayout.BeginHorizontal();
		newDialogueSceneName = EditorGUILayout.TextField(newDialogueSceneName);
		GUI.enabled = newDialogueSceneName.Length > 0 && Resources.Load<DialogueScene>("BS_DialogueSystem/DialogueScene" + newDialogueSceneName) == null;
		if (GUILayout.Button("Save as new", GUILayout.Width(100)))
		{
			SaveAsNew();
		}
		GUILayout.EndHorizontal();

		if (!GUI.enabled)
		{
			GUIStyle style = new GUIStyle();
			style.normal.textColor = Color.red;
			if (newDialogueSceneName.Length <= 0)
			{
				EditorGUILayout.LabelField("Name must be longer than 0!", style);
			}
			else
			{
				EditorGUILayout.LabelField("The same named file already exists!", style);
			}
		}
		GUI.enabled = true;
	}

	private void SaveAsNew()
	{

		DialogueScene newDialogueScene = ScriptableObject.CreateInstance<DialogueScene>();
		newDialogueScene.dialogues = dialogues;

		string dir = Application.dataPath;

		if (!Directory.Exists(dir + "/Resources/BS_DialogueSystem/DialogueScene"))
		{
			Debug.Log("Creating directory for DialogueScene assets...");
			try
			{
				Directory.CreateDirectory(dir + "/Resources/BS_DialogueSystem/DialogueScene");
			}
			catch
			{
				Debug.LogError("Creating directory Failed!");
				throw;
			}
			Debug.Log("Creating directory Success!");
		}
		try
		{
			AssetDatabase.CreateAsset(newDialogueScene, "Assets/Resources/BS_DialogueSystem/DialogueScene/" + newDialogueSceneName + ".asset");
		}
		catch
		{
			Debug.LogError("Creating" + newDialogueSceneName + ".asset Failed!");
			throw;
		}
		Debug.Log("Creating " + newDialogueSceneName + ".asset Success!");
		dialogueScene = newDialogueScene;

	}

	private void DialoguesGUI()
	{
		dialoguesScroll = GUILayout.BeginScrollView(dialoguesScroll);

		for (int i = 0; i < dialogues.Count; i++)
		{
			GUILayout.BeginHorizontal();
			dialogueFoldouts[i] = EditorGUILayout.Foldout(dialogueFoldouts[i], "Dialogue " + i.ToString());
			Dialogue dialogue = new Dialogue(dialogues[i]);
			EditorGUILayout.LabelField(dialogue.characterName + ": " +
				dialogue.dialogue.Substring(0, Math.Min(20, dialogue.dialogue.Length)));
			GUILayout.EndHorizontal();

			EditorGUI.indentLevel++;
			if (dialogueFoldouts[i])
			{
				dialogue.characterName = EditorGUILayout.TextField("Character name", dialogue.characterName);
				dialogue.characterCount = EditorGUILayout.IntField("Character count", dialogue.characterCount);

				while (dialogue.characterIDs.Count < dialogue.characterCount)
				{
					dialogue.characterIDs.Add(0);
				}
				while (dialogue.expressions.Count < dialogue.characterCount)
				{
					dialogue.expressions.Add(CharacterExpression.DEFAULT);
				}
				while (dialogue.characterIDs.Count > dialogue.characterCount)
				{
					dialogue.characterIDs.RemoveAt(dialogue.characterIDs.Count - 1);
				}
				while (dialogue.expressions.Count > dialogue.characterCount)
				{
					dialogue.expressions.RemoveAt(dialogue.expressions.Count - 1);
				}

				string[] names = new string[CharacterResourceEditorWindow.characters.Count];
				int k = 0;
				foreach (var key in CharacterResourceEditorWindow.characters.Keys)
				{
					names[k++] = CharacterResourceEditorWindow.characters[key].characterName;
				}

				EditorGUI.indentLevel++;
				for (int j = 0; j < dialogue.characterCount; j++)
				{
					GUILayout.FlexibleSpace();
					dialogue.characterIDs[j] = EditorGUILayout.IntPopup("Character " + j.ToString(), dialogue.characterIDs[j], names, CharacterResourceEditorWindow.characters.Keys.ToArray());
					dialogue.expressions[j] = (CharacterExpression)EditorGUILayout.EnumPopup("Expression " + j.ToString(), dialogue.expressions[j]);
				}
				EditorGUI.indentLevel--;
				EditorGUILayout.LabelField("Dialogue");
				dialogue.dialogue = EditorGUILayout.TextArea(dialogue.dialogue,GUILayout.Height(75));
			}
			dialogues[i] = dialogue;

			EditorGUILayout.BeginHorizontal();
			GUILayout.FlexibleSpace();
			if (i > 0 && GUILayout.Button("↑", GUILayout.Width(20)))
			{
				dialogues[i] = dialogues[i - 1];
				dialogues[i - 1] = dialogue;
				break;
			}
			if (i < dialogues.Count - 1 && GUILayout.Button("↓", GUILayout.Width(20)))
			{
				dialogues[i] = dialogues[i + 1];
				dialogues[i + 1] = dialogue;
				break;
			}
			if (GUILayout.Button("+", GUILayout.Width(20)))
			{
				Dialogue newDialogue = new Dialogue(dialogue);
				dialogues.Insert(i + 1, newDialogue);
				dialogueFoldouts.Add(true);
				break;
			}
			if (GUILayout.Button("-", GUILayout.Width(20)))
			{
				dialogues.RemoveAt(i);
				dialogueFoldouts.RemoveAt(i);
				break;
			}
			EditorGUILayout.EndHorizontal();
			EditorGUI.indentLevel--;
			Save();
		}

		GUILayout.EndScrollView();
	}

	#endregion
	
	private void AddNewDialogue(Dialogue dialogue)
	{
		dialogues.Add(dialogue);
		dialogueFoldouts.Add(true);
	}

	private void DialogueToEditorLayout(Dialogue dialogue)
    {

    }
}
#endif