﻿/*
MIT License

Copyright(c) 2019 Mitchel Thompson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Reflection;
using System.IO;
using UnityEngine.UIElements;
using UnityEditor.UIElements;

namespace Arugula.Audio
{

    [CustomPropertyDrawer(typeof(Phonic.Options), true)]
    public class OptionsDrawer : PropertyDrawer
    {
        static bool isExpanded;
        static bool initialized;

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            property.isExpanded = false;
            if (!initialized)
            {
                initialized = true;
                isExpanded = EditorPrefs.GetBool("Phonic.OptionsDrawer", false);
            }

            string basePath = property.propertyPath;

            position.height = EditorGUIUtility.singleLineHeight;
            bool expand = EditorGUI.Foldout(position, isExpanded, label);
            if (expand != isExpanded)
            {
                isExpanded = expand;
                EditorPrefs.SetBool("Phonic.OptionsDrawer", isExpanded);
            }

            Event ev = Event.current;
            if (ev.type == EventType.MouseUp && ev.button > 0)
            {
                if (position.Contains(ev.mousePosition))
                {
                    DefaultsContextMenu();
                }
            }

            if (!isExpanded)
                return;


            EditorGUI.indentLevel++;
            property.NextVisible(true);

            position.y += EditorGUIUtility.singleLineHeight;
            EditorGUI.PropertyField(position, property);

            int maskVal = property.intValue;
            int i = 0;
            while (property.NextVisible(false))
            {
                if (!property.propertyPath.Contains(basePath))
                    break;
                position.y += EditorGUIUtility.singleLineHeight;
                EditorGUI.BeginDisabledGroup((maskVal & (1 << i)) == 0);
                EditorGUI.PropertyField(position, property);
                EditorGUI.EndDisabledGroup();
                i++;
            }
            EditorGUI.indentLevel--;
        }

        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            if (!isExpanded)
                return EditorGUIUtility.singleLineHeight;

            return 250;
        }

        void DefaultsContextMenu()
        {
            GenericMenu menu = new GenericMenu();

            //TODO:  Get these and apply them as properties :(
            menu.AddItem(new GUIContent("2D"), false, () => { });
            menu.AddItem(new GUIContent("3D"), false, () => { });

            menu.ShowAsContext();
        }
    }

    [CustomPropertyDrawer(typeof(PhonicSound))]
    public class SoundDrawer : PropertyDrawer
    {
        public struct ValuePair
        {
            public PhonicGroup group;
            public AudioClip clip;
            public SerializedProperty property;

            public ValuePair(PhonicGroup group, AudioClip clip, SerializedProperty property)
            {
                this.group = group;
                this.clip = clip;
                this.property = property;
            }
        }

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            if (property.propertyType != SerializedPropertyType.String)
            {
                EditorGUI.LabelField(position, "ERROR: " + "Only string fields!");
                return;
            }

            position = EditorGUI.PrefixLabel(position, label);
            var propertyStringValue = property.stringValue;

            PhonicTools.PlayClipButton(propertyStringValue, ref position);
            //position.x += 40;
            //position.width -= 40;
            if (GUI.Button(position, string.IsNullOrEmpty(propertyStringValue) ? "<None>" : propertyStringValue, EditorStyles.popup))
            {
                Selector(property);
            }
        }

        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            return 18;
        }

        void Selector(SerializedProperty property)
        {
            GenericMenu menu = new GenericMenu();
            //PopulateMenu(menu, property, this.TargetAttribute, data);

            var groupGUIDs = AssetDatabase.FindAssets("t:PhonicGroup");

            menu.AddItem(new GUIContent("<None>"), false, HandleSelect, new ValuePair(null, null, property));
            foreach (var b in groupGUIDs)
            {
                string assetPath = AssetDatabase.GUIDToAssetPath(b.ToString());
                string groupName = Path.GetFileNameWithoutExtension(assetPath);
                var group = AssetDatabase.LoadAssetAtPath<PhonicGroup>(assetPath as string);

                menu.AddItem(new GUIContent(groupName + "/Random"), false, HandleSelect, new ValuePair(group, null, property));

                for (int i = 0; i < group.clips.Count; i++)
                {
                    if (group.clips[i] == null)
                        continue;

                    string name = groupName + "/" + group.clips[i].name;
                    menu.AddItem(new GUIContent(name), property.stringValue == name, HandleSelect, new ValuePair(group, group.clips[i], property));
                }
            }

            menu.ShowAsContext();
        }

        void HandleSelect(object data)
        {

            ValuePair pair = (ValuePair)data;

            if (pair.group == null && pair.clip == null)
            {
                pair.property.stringValue = "";
            }
            else if (pair.clip == null)
            {
                pair.property.stringValue = pair.group.name + "/Random";
            }
            else
            {
                pair.property.stringValue = pair.group.name + "/" + pair.clip.name;
            }


            pair.property.serializedObject.ApplyModifiedProperties();
        }

    }
}
