using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using SimpleJSON;
using SFB;
using System.IO;

public class JsonEditorWindow : EditorWindow
{

    public string RawJson = "";
    public string OldJson = "";
    public JSONNode jsonRoot;


    private Vector2 scrollpos;
    private Dictionary<JSONNode, bool> FoldHash;
    private bool isFile = false;
    private string FilePath;

    // Add menu named "My Window" to the Window menu
    [MenuItem("Tools/Editor Add On/Json Editor")]
    public static void Init()
    {
        // Get existing open window or if none, make a new one:
        JsonEditorWindow window = (JsonEditorWindow)EditorWindow.GetWindow(typeof(JsonEditorWindow));

        window.Initialise("");
        window.Show();
    }

    public static void Init(string json)
    {
        // Get existing open window or if none, make a new one:
        JsonEditorWindow window = (JsonEditorWindow)EditorWindow.GetWindow(typeof(JsonEditorWindow));

        window.Initialise(json);
        window.Show();
    }


    private void Initialise(string json = "")
    {
        if (!string.IsNullOrEmpty(json))
            RawJson = json;
        
    }

    public void OnGUI()
    {
        inputGUI();
        JsonGUI();
    }

    private void inputGUI()
    {
        EditorGUILayout.BeginHorizontal();
        if (!isFile)
        {
            if (GUILayout.Button("Open File",GUILayout.Width(80)))
            {
                FilePath = StandaloneFileBrowser.OpenFilePanel("Open Location File", FilePath, "txt", false)[0];

                if (File.Exists(FilePath))
                {
                    RawJson = File.ReadAllText(FilePath);
                    isFile = true;
                }
                else
                {
                    RawJson = null;
                    isFile = false;
                }
            }
        }
        else
        {
            if (GUILayout.Button("Clear", GUILayout.Width(80)))
            {
                RawJson = null;
                isFile = false;
            }
        }

        if (!isFile)
        {
            RawJson = EditorGUILayout.TextField(RawJson);
        }
        else
        {         
            EditorGUILayout.LabelField(Path.GetFileName(FilePath));      
        }


        EditorGUILayout.EndHorizontal();


        if (OldJson == RawJson)
            return;

        OldJson = RawJson;

        try
        {
            jsonRoot = JSON.Parse(RawJson);
            FoldHash = new Dictionary<JSONNode, bool>();
        }
        catch
        {
            Debug.LogWarning("Can not parse Json string");
            jsonRoot = null;
        }
    }

    private void JsonGUI()
    {
        scrollpos =  GUILayout.BeginScrollView(scrollpos);
        DrawNode(jsonRoot);
        GUILayout.EndScrollView();

        if (jsonRoot != null)
        {
            RawJson = jsonRoot.ToString();
            OldJson = jsonRoot.ToString();
        }

    }

    private void DrawJsonObject(JSONNode node,string key)
    {
        if (!FoldHash.ContainsKey(node))
            FoldHash.Add(node, false);

        FoldHash[node] = EditorGUILayout.Foldout(FoldHash[node], key);
        if (!FoldHash[node])
            return;

        foreach (KeyValuePair<string, JSONNode> child in node)
        {
            DrawNode(child.Value,child.Key);
        }
    }

    private void DrawJsonArray(JSONNode node, string key)
    {
        if (!FoldHash.ContainsKey(node))
            FoldHash.Add(node, false);

        FoldHash[node] = EditorGUILayout.Foldout(FoldHash[node], key);
        if (!FoldHash[node])
            return;

        foreach (JSONNode child in node)
            DrawNode(child);
    }

    

    private void DrawNode(JSONNode node,string key = "")
    {
        if (node == null) return;

        EditorGUI.indentLevel++;

        switch (node.Tag)
        {
            case JSONNodeType.Object:
                DrawJsonObject(node,key);
                break;
            case JSONNodeType.Array:
                DrawJsonArray(node,key);
                break;
            default:
                EditorGUILayout.BeginHorizontal();
                node.Value =  EditorGUILayout.TextField(key,node.Value);

                EditorGUILayout.EndHorizontal();
                break;
        }

        EditorGUI.indentLevel--;
    }

    private void DebugNode(JSONNode node)
    {
        EditorGUILayout.TextArea(node.ToString(1));
    }


}
