using System;
using System.Text;
using UnityEditor;
using UnityEngine;

namespace Ingvar.LiveWatch.Editor
{
    [Serializable]
    public class InfoGUI
    {
        public WatchVariable SelectedVariable { get; set; }
        public bool IsTitleSelected { get; set; }
        public int SelectedColumn { get; set; }

        private Rect contentRect;
        private Vector2 scrollPosition;
        
        public void OnGUI(Rect areaRect)
        {
            EditorGUI.DrawRect(areaRect.Extrude(ExtrudeFlags.Top, 1), Colors.Background);

            if (SelectedVariable == null)
            {
                return;
            }

            if (IsTitleSelected)
            {
                DrawForTitle(areaRect);
            }
            else if (SelectedVariable.HasValues)
            {
                DrawForValues(areaRect);
            }
        }

        private void DrawForTitle(Rect rect)
        {
            contentRect = rect.Extrude(ExtrudeFlags.All, -2);

            GUILayout.BeginArea(contentRect);
            scrollPosition = GUILayout.BeginScrollView(scrollPosition);
            
            DrawVariableName();

            GUILayout.FlexibleSpace();
            GUILayout.EndScrollView();
            GUILayout.EndArea();
        }

        private void DrawForValues(Rect rect)
        {
            if (!SelectedVariable.Values.AnyAt(SelectedColumn))
            {
                return;
            }

            contentRect = rect.Extrude(ExtrudeFlags.All, -2);

            GUILayout.BeginArea(contentRect);
            scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUIStyle.none);
            
            DrawValueText();
            
            GUILayout.EndScrollView();
            GUILayout.EndArea();
        }

        private void DrawVariableName()
        {
                DrawLabel(SelectedVariable.Name, Styles.InfoValueText);
        }
        
        private void DrawValueText()
        {
            var selectedValueText = SelectedVariable.GetValueText(SelectedColumn);

            if (string.IsNullOrWhiteSpace(selectedValueText))
            {
                return;
            }
        
                DrawLabel(selectedValueText, Styles.InfoValueText);
        }
        
        private void DrawLabel(string text, GUIStyle textStyle)
        {
            var content = WatchEditorServices.GUICache.GetContent(text);
            var estimatedHeight = textStyle.CalcHeight(content, contentRect.width);
            
            EditorGUILayout.SelectableLabel(
                text,   
                textStyle, 
                GUILayout.ExpandWidth(true), 
                GUILayout.ExpandHeight(false),
                GUILayout.Height(estimatedHeight));
        }
        
    }
}