﻿/*
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.IO;
using System.Reflection;
using System.Linq;

namespace Arugula.Audio
{
    public static class PhonicTools
    {
        static bool initialized = false;
        static GUIContent[] playIcons;
        static System.Type audioUtilType;
        static System.Type[] audioUtilParamTypes;

        static PhonicTools()
        {
            Assembly assembly = typeof(AudioImporter).Assembly;
            audioUtilType = assembly.GetType("UnityEditor.AudioUtil");
            audioUtilParamTypes = new System.Type[3] { typeof(AudioClip), typeof(int), typeof(bool) };
            Initialize();
        }

        static void Initialize()
        {
            if (initialized)
                return;

            try
            {
                playIcons = new GUIContent[2];
                playIcons[0] = EditorGUIUtility.IconContent("preAudioPlayOff", "|Play");
                playIcons[1] = EditorGUIUtility.IconContent("preAudioPlayOn", "|Stop");

                initialized = true;
            }
            catch
            {

            }

        }

        [MenuItem("Assets/Create/Phonic Group")]
        static void CreatePhonicGroup()
        {
            string path = "Assets/PhonicGroup.asset";

            if (Selection.activeObject != null)
            {
                string assetPath = AssetDatabase.GetAssetPath(Selection.activeObject);
                string extension = Path.GetExtension(assetPath);

                if (extension == "")
                    path = assetPath + "/PhonicGroup.asset";
                else
                    path = Path.GetDirectoryName(assetPath) + "/PhonicGroup.asset";
            }

            var group = PhonicGroup.CreateInstance<PhonicGroup>();

            if (Selection.objects.Length > 0)
            {
                foreach (var o in Selection.objects)
                {
                    if (o is AudioClip)
                    {
                        group.clips.Add(o as AudioClip);
                    }
                }

            }

            AssetDatabase.CreateAsset(group, path);
        }

        public static bool PlayClipButton()
        {
            Initialize();

            if (GUILayout.Button(playIcons[0], "preButton", GUILayout.Width(40)))
            {
                return true;
            }

            return false;
        }

        public static bool PlayClipButton(string soundPath, ref Rect position)
        {
            Initialize();

            Rect drawRect = position;
            drawRect.width = 40;

            position.x += 40;
            position.width -= 40;


            EditorGUI.BeginDisabledGroup(soundPath == "" || soundPath == null);
            if (GUI.Button(drawRect, playIcons[0], "preButton"))
            {
                //sound path lookup
                var table = GetGroupTable();

                string[] chunks = soundPath.Split('/');
                string groupName = chunks[0].ToLower();
                string soundName = chunks[1].ToLower();

                var group = table[groupName];
                group.BuildTable();

                if (soundName == "random")
                {
                    PlayClip(group.GetRandomClip());
                }
                else
                {
                    PlayClip(group.GetClip(soundName));
                }



                return true;
            }
            EditorGUI.EndDisabledGroup();

            return false;
        }

        public static bool PlayClipButton(AudioClip clip)
        {
            Initialize();

            EditorGUI.BeginDisabledGroup(clip == null);
            bool playing = false;
            if (GUILayout.Button(playIcons[0], "preButton", GUILayout.Width(40)))
            {
                StopAllClips();
                PlayClip(clip);
                playing = true;
            }
            EditorGUI.EndDisabledGroup();

            return playing;
        }

        public static void PlayClip(AudioClip clip)
        {
            if (clip == null)
            {
                Debug.LogWarning("[Phonic] Cannot play Null clip!");
                return;
            }

            object[] objs = { clip, 0, false };
            MethodInfo method = audioUtilType.GetMethod("PlayClip", audioUtilParamTypes);
            method.Invoke(null, BindingFlags.Static | BindingFlags.Public, null, objs, null);
        }

        public static void StopAllClips()
        {
            MethodInfo method = audioUtilType.GetMethod("StopAllClips");
            method.Invoke(null, BindingFlags.Static | BindingFlags.Public, null, null, null);
        }

        //TODO:  Cache this?
        public static PhonicGroup[] GetAllGroups()
        {
            var groupGUIDs = AssetDatabase.FindAssets("t:PhonicGroup");

            List<PhonicGroup> groups = new List<PhonicGroup>();
            foreach (var guid in groupGUIDs)
            {
                string assetPath = AssetDatabase.GUIDToAssetPath(guid);
                var group = AssetDatabase.LoadAssetAtPath<PhonicGroup>(assetPath);
                groups.Add(group);
            }

            return groups.ToArray();
        }

        public static Dictionary<string, PhonicGroup> GetGroupTable()
        {
            var groups = GetAllGroups();
            Dictionary<string, PhonicGroup> groupTable = new Dictionary<string, PhonicGroup>();

            foreach (var b in groups)
            {
                if (groupTable.ContainsKey(b.name.ToLower()))
                    continue;

                groupTable.Add(b.name.ToLower(), b);
            }

            return groupTable;
        }
    }
}
