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

using System.Collections.Generic;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.UIElements;

namespace BansheeGz.BGDatabase.Editor
{
    public abstract class BGGCTableADrawer<T> : BGGCActionDrawer<T> where T : BGGCTableA
    {
        protected SerializedProperty metaProperty;

        protected override void Create()
        {
            var repo = BGRepo.I;

            var metaField = HiddenTextField("tableId", out metaProperty);

            var metas = repo.FindMetas();
            metas.Insert(0, null);
            var currentMeta = action.Meta;
            var popup = new PopupField<BGMetaEntity>("Table", metas, FindIndex(metas, currentMeta), Format, Format);
            Add(popup);

            popup.TrackPropertyValue(metaProperty, prop =>
            {
                action.ResetMeta();
                popup.index = FindIndex(metas, prop.stringValue);
            });
            popup.RegisterValueChangedCallback(evt => metaField.value = evt.newValue?.Id.ToString());
        }

        private static int FindIndex(List<BGMetaEntity> metas, BGMetaEntity currentMeta) => currentMeta == null ? 0 : FindIndex(metas, currentMeta.Id.ToString());
        private static int FindIndex(List<BGMetaEntity> metas, string id)
        {
            if (string.IsNullOrEmpty(id)) return 0;
            var index = metas.FindIndex(meta => meta?.Id.ToString().Equals(id) ?? false);
            return index == -1 ? 0 : index;
        }


        protected static string Format(BGMetaObject meta) => meta == null ? "[None]" : meta.Name;

        protected TextField HiddenTextField(string propertyName, out SerializedProperty property)
        {
            property = Find(propertyName);
            var metaField = new TextField
            {
                style =
                {
                    display = DisplayStyle.None
                }
            };
            metaField.BindProperty(property);
            Add(metaField);
            return metaField;
        }
    }
}