/*
<copyright file="BGGCTableA.cs" company="BansheeGz">
    Copyright (c) 2018-2021 All Rights Reserved
</copyright>
*/

using System.Collections.Generic;
using GameCreator.Core;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace BansheeGz.BGDatabase
{
    /// <summary>
    /// reference to a table 
    /// </summary>
    [BGPlugin(Version = "1.2")]
    public abstract class BGGCTableA : BGGCAction
    {
        [SerializeField] [HideInInspector] private string tableId;

        private BGMetaEntity meta;

        public BGMetaEntity Meta
        {
            get
            {
                if (meta != null && !meta.IsDeleted) return meta;
                meta = null;
                if (string.IsNullOrEmpty(tableId)) return null;
                if (!BGId.TryParse(tableId, out var metaId)) return null;

                meta = BGRepo.I.GetMeta(metaId);
                return meta;
            }
        }
        // +--------------------------------------------------------------------------------------+
        // | EDITOR                                                                               |
        // +--------------------------------------------------------------------------------------+

#if UNITY_EDITOR
        

        protected override void OnDisableEditorChild () => meta = null;

        protected virtual void OnMetaChange()
        {
        }

        public override void EditorGui()
        {
            base.EditorGui();
            //meta
            var repo = BGRepo.I;
            var currentMeta = Meta;
            var metas = repo.FindMetas();
            var currentMetaIndex = 0;
            for (var i = 0; i < metas.Count; i++)
            {
                var m = metas[i];
                if (m == currentMeta) currentMetaIndex = i + 1;
            }

            var metaOptions = new List<string>() {"[None]"};
            metaOptions.AddRange(metas.ConvertAll(m => m.Name));
            var newMetaIndex = EditorGUILayout.Popup("Meta", currentMetaIndex, metaOptions.ToArray(),
                currentMetaIndex == 0 ? new GUIStyle(EditorStyles.popup) {normal = {textColor = Color.red}} : EditorStyles.popup);
            if (newMetaIndex != currentMetaIndex)
            {
                if (newMetaIndex == 0)
                {
                    currentMeta = null;
                    metaIdProp = null;
                }
                else
                {
                    currentMeta = metas[newMetaIndex - 1];
                    metaIdProp = currentMeta.Id.ToString();
                }
                meta = null;
                OnMetaChange();
                GUIUtility.ExitGUI();
            }
        }

        protected string metaIdProp
        {
            get => Prop(nameof(tableId)).stringValue;
            set => Prop(nameof(tableId)).stringValue = value;
        }
#endif
        
    }
}