﻿/*
MIT License

Copyright(c) 2019 Mitchel Thompson
www.angryarugula.com

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 UnityEngine.Audio;
#if UNITY_EDITOR
using UnityEditor;
using System.Reflection;
using System.Linq;
#endif

namespace Arugula.Audio
{
    public class PhonicLoader : MonoBehaviour
    {
        public enum DefaultMode { TwoD, ThreeD, None }

        public List<PhonicGroup> groups = new List<PhonicGroup>();
        public bool autoInstantiate = true;
        public int maxChannels = 20;
        public DefaultMode defaultMode = DefaultMode.None;
        public AudioMixerGroup defaultOutput;
        public bool unloadOnDestroy = false;
        void Awake()
        {
            if (autoInstantiate)
            {
                Phonic.MaxChannels = maxChannels;
                Phonic.Instantiate();
            }

            Phonic.Defaults.Default2D.output = defaultOutput;
            Phonic.Defaults.Default3D.output = defaultOutput;

            switch (defaultMode)
            {
                case DefaultMode.None:
                    break;
                case DefaultMode.ThreeD:
                    Phonic.DefaultOptions = Phonic.Defaults.Default3D;
                    break;
                case DefaultMode.TwoD:
                    Phonic.DefaultOptions = Phonic.Defaults.Default2D;
                    break;
            }

            foreach (var g in groups)
                Phonic.Load(g);
        }

        void OnDestroy()
        {
            if (unloadOnDestroy)
                foreach (var g in groups)
                    Phonic.Unload(g);
        }

#if UNITY_EDITOR
        [ContextMenu("Add Required Groups")]
        void AddRequiredGroups()
        {
            var monoBehaviours = Resources.FindObjectsOfTypeAll<MonoBehaviour>().Where(
                mb => !EditorUtility.IsPersistent(mb.transform.root.gameObject) &&
                !(mb.gameObject.hideFlags == HideFlags.NotEditable ||
                mb.gameObject.hideFlags == HideFlags.HideAndDontSave)).ToList();


            List<string> requiredGroups = new List<string>();

            foreach (var m in monoBehaviours)
            {
                var fields = m.GetType().GetFields();
                foreach (var f in fields)
                {
                    if (f.GetCustomAttribute(typeof(PhonicSound)) != null)
                    {
                        List<string> soundPaths = new List<string>();
                        if (f.FieldType.IsArray)
                        {
                            object obj = f.GetValue(m);
                            if (obj is string[])
                            {
                                foreach (var str in (string[])obj)
                                    soundPaths.Add(str);
                            }
                            else if (obj is List<string>)
                            {
                                foreach (var str in (List<string>)obj)
                                    soundPaths.Add(str);
                            }
                            string[] arr = (string[])f.GetValue(m);
                        }
                        else
                        {
                            soundPaths.Add((string)f.GetValue(m));
                        }

                        foreach (var soundPath in soundPaths)
                        {
                            if (string.IsNullOrEmpty(soundPath))
                                continue;

                            string groupName = soundPath.Split('/').FirstOrDefault();

                            if (!requiredGroups.Contains(groupName))
                                requiredGroups.Add(groupName);
                        }

                    }
                }
            }


            foreach (var r in groups)
                requiredGroups.Remove(r.name);

            if (requiredGroups.Count == 0)
            {
                Debug.Log("No new PhonicGroups needed!");
                return;
            }

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

            foreach (var guid in groupGUIDs)
            {
                string assetPath = AssetDatabase.GUIDToAssetPath(guid);
                string groupName = System.IO.Path.GetFileNameWithoutExtension(assetPath);
                if (requiredGroups.Contains(groupName))
                {
                    groups.Add(AssetDatabase.LoadAssetAtPath<PhonicGroup>(assetPath));
                    requiredGroups.Remove(groupName);
                }
            }

            EditorUtility.SetDirty(this);

        }
#endif
    }

}
