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

namespace JLGames.RocketDriver.Editor
{
    [CanEditMultipleObjects, CustomEditor(typeof(DefaultAsset))]
    public class LuaInspector : UnityEditor.Editor
    {
        private GUIStyle m_TextStyle;

        public override void OnInspectorGUI()
        {
            if (m_TextStyle == null)
            {
                m_TextStyle = "ScriptText";
            }

            var enabled = GUI.enabled;
            GUI.enabled = true;
            var assetPath = AssetDatabase.GetAssetPath(target);
            if (assetPath.EndsWith(".lua") || assetPath.EndsWith(".lua.txt") || assetPath.EndsWith(".lua.bytes"))
            {
                string luaFile = File.ReadAllText(assetPath);
                string text;
                if (base.targets.Length > 1)
                {
                    text = Path.GetFileName(assetPath);
                }
                else
                {
                    text = luaFile;
                    if (text.Length > 7000)
                    {
                        text = text.Substring(0, 7000) + "...\n\n<...etc...>";
                    }
                }

                var rect = GUILayoutUtility.GetRect(new GUIContent(text), m_TextStyle);
                rect.x = 0f;
                rect.y -= 3f;
                rect.width = EditorGUIUtility.currentViewWidth + 1f;
                GUI.Box(rect, text, m_TextStyle);
            }

            GUI.enabled = enabled;
        }
    }
}