using System.Collections.Generic;
using gay.lilyy.Common;
using gay.lilyy.MenuIconReplacer;
using nadena.dev.ndmf;
using nadena.dev.ndmf.vrchat;
using NUnit.Framework.Constraints;
using UnityEditor;
using UnityEngine;
using VRC.SDK3.Avatars.ScriptableObjects;
using static VRC.SDK3.Avatars.ScriptableObjects.VRCExpressionsMenu;

[assembly: ExportsPlugin(typeof(MenuIconReplacerPlugin))]

namespace gay.lilyy.MenuIconReplacer
{
    public class MenuIconReplacerPlugin : Plugin<MenuIconReplacerPlugin>
    {
        public override string DisplayName => "MenuIconReplacer";
        public override string QualifiedName => "gay.lilyy.MenuIconReplacer";

        protected override void Configure()
        {
            InPhase(BuildPhase.Optimizing).BeforePlugin("gay.lilyy.MenuIconRemover").Run("ReplaceMenuIcons", ctx =>
            {
                var obj = ComponentHelper.GetComponentInChildrenWithError<MenuIconReplacerConfig>(ctx.AvatarRootObject);
                if (obj != null)
                {
                    var descriptor = ctx.VRChatAvatarDescriptor();
                    descriptor.expressionsMenu = RecurseMenu(obj, descriptor.expressionsMenu);
                    Object.DestroyImmediate(obj);
                }
            });
        }

        private VRCExpressionsMenu RecurseMenu(MenuIconReplacerConfig cfg, VRCExpressionsMenu menu)
        {
            if (menu == null) return null;

            var newMenu = ScriptableObject.CreateInstance<VRCExpressionsMenu>();
            newMenu.controls = new List<Control>();

            foreach (var control in menu.controls)
            {
                var icon = control.icon;
                foreach (var entry in cfg.replacements)
                {
                    if (entry.from == icon) {
                        icon = entry.to;
                    }
                }
                var newControl = new Control
                {
                    name = control.name,
                    type = control.type,
                    icon = icon,
                    parameter = control.parameter,
                    subMenu = RecurseMenu(cfg, control.subMenu),
                    value = control.value,
                    style = control.style,
                    labels = control.labels,
                    subParameters = control.subParameters
                };
                newMenu.controls.Add(newControl);
            }

            return newMenu;
        }
    }
}
