/*
<copyright file="BGGCCellADrawer.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 class BGGCCellADrawer<T> : BGGCRowADrawer<T> where T : BGGCCellA
    {
        
        protected SerializedProperty fieldProperty;
        
        protected override void Create()
        {
            base.Create();
            
            var metaField = HiddenTextField("fieldId", out fieldProperty);

            var fields = GetFields();
            var popup = new PopupField<BGField>("Field", fields, FindIndex(fields, fieldProperty.stringValue), Format, Format);
            Add(popup);

            popup.TrackPropertyValue(fieldProperty, prop => popup.index = FindIndex(GetFields(), prop.stringValue));
            popup.RegisterValueChangedCallback(evt => metaField.value = evt.newValue?.Id.ToString());

            popup.TrackPropertyValue(metaProperty, prop =>
            {
                popup.choices = GetFields();
                metaField.value = null;
                popup.index = 0;
            });
            
        }

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

        private List<BGField> GetFields()
        {
            var result = new List<BGField> { null };
            var currentMeta = action.Meta;
            currentMeta?.ForEachField(field => result.Add(field), action.IsSupported);
            return result;
        }
    }
}