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

namespace Arugula.Audio
{
    public sealed class PhonicOption
    {
        internal Phonic.OptionType type;
        internal object value;

        internal PhonicOption(Phonic.OptionType type, object value)
        {
            this.type = type;
            this.value = value;
        }
    }

    public class Phonic : MonoBehaviour
    {
        public enum OptionType
        {
            Position = 1 << 0,
            Volume = 1 << 1,
            Pitch = 1 << 2,
            PanStereo = 1 << 3,
            SpatialBlend = 1 << 4,
            Output = 1 << 5,
            DopplerLevel = 1 << 6,
            Spread = 1 << 7,
            RolloffMode = 1 << 8,
            MinDistance = 1 << 9,
            MaxDistance = 1 << 10
        }

        [System.Serializable]
        public class Options
        {
            [EnumFlag]
            public OptionType mask;
            public Vector3 position;
            [MinMax]
            public Vector2 volume = Vector2.one;
            [MinMax(-3, 3f)]
            public Vector2 pitch = Vector2.one;
            [Range(-1, 1)]
            public float panStereo = 0;
            [Range(0, 1)]
            public float spatialBlend = 0;
            public AudioMixerGroup output;
            [Range(0, 5)]
            public float dopplerLevel = 1;
            [Range(0, 360)]
            public float spread = 0;
            public AudioRolloffMode rollOffMode;
            public float minDistance = 1;
            public float maxDistance = 500;

            internal void Apply(AudioSource source)
            {
                if (mask.HasFlag(OptionType.Position)) source.transform.position = position;
                if (mask.HasFlag(OptionType.Volume)) source.volume = Random.Range(volume.x, volume.y);
                if (mask.HasFlag(OptionType.Pitch)) source.pitch = Random.Range(pitch.x, pitch.y);
                if (mask.HasFlag(OptionType.PanStereo)) source.panStereo = panStereo;
                if (mask.HasFlag(OptionType.SpatialBlend)) source.spatialBlend = spatialBlend;
                if (mask.HasFlag(OptionType.Output)) source.outputAudioMixerGroup = output;
                if (mask.HasFlag(OptionType.DopplerLevel)) source.dopplerLevel = dopplerLevel;
                if (mask.HasFlag(OptionType.Spread)) source.spread = spread;
                if (mask.HasFlag(OptionType.RolloffMode)) source.rolloffMode = rollOffMode;
                if (mask.HasFlag(OptionType.MinDistance)) source.minDistance = minDistance;
                if (mask.HasFlag(OptionType.MaxDistance)) source.minDistance = maxDistance;
            }
        }

        public class Defaults
        {
            static Defaults()
            {
                Default2D = new Options();
                Default2D.mask = (OptionType)int.MaxValue;
                Default2D.volume = Vector2.one;
                Default2D.pitch = Vector2.one;
                Default2D.panStereo = 0;
                Default2D.spatialBlend = 0;
                Default2D.output = null;
                Default2D.dopplerLevel = 1;
                Default2D.spread = 0;
                Default2D.rollOffMode = AudioRolloffMode.Logarithmic;
                Default2D.minDistance = 1;
                Default2D.maxDistance = 500;

                Default3D = new Options();
                Default3D.mask = (OptionType)int.MaxValue;
                Default3D.volume = Vector2.one;
                Default3D.pitch = Vector2.one;
                Default3D.panStereo = 0;
                Default3D.spatialBlend = 1;
                Default3D.output = null;
                Default3D.dopplerLevel = 1;
                Default3D.spread = 0;
                Default3D.rollOffMode = AudioRolloffMode.Logarithmic;
                Default3D.minDistance = 1;
                Default3D.maxDistance = 500;
            }

            public static Options Default2D;
            public static Options Default3D;
        }

        static int maxChannels = 20;
        public static Options DefaultOptions;
        public static int MaxChannels
        {
            get
            {
                return maxChannels;
            }
            set
            {
                if (Instance != null)
                {
                    if (Instance.channels.Length != value)
                    {
                        Instance.Cleanup();
                        Instance.Initialize();
                    }
                }
            }
        }

        static Phonic Instance;
        static Dictionary<string, PhonicGroup> groups;

        static Phonic()
        {
            DefaultOptions = Defaults.Default2D;

            groups = new Dictionary<string, PhonicGroup>();
        }

        public static void Instantiate()
        {
            if (Instance != null)
            {
                //already spawned
            }
            else
            {
                new GameObject("Phonic", typeof(Phonic));
            }
        }

        public static void Load(PhonicGroup group)
        {
            if (group == null)
                return;

            if (groups.ContainsKey(group.name.ToLower()))
                return;

            group.BuildTable();
            groups.Add(group.name.ToLower(), group);
        }

        public static void Unload(PhonicGroup group)
        {
            if (group == null)
                return;

            //TODO:  forcefully clear and audiosources that still have reference to group contents?
            groups.Remove(group.name);
        }

        public static AudioSource Play(string soundPath, params PhonicOption[] options)
        {
            if (Instance == null)
            {
                Debug.LogWarning("[Phonic] Not initialized!");
                return null;
            }


            if (soundPath == "" || soundPath == null)
            {
                return null;
            }
            string[] chunks = soundPath.Split('/');
            string groupName = chunks[0].ToLower();
            string soundName = chunks[1].ToLower();


            var group = groups[groupName];
            if (group == null)
            {
                Debug.LogWarning("[Phonic] No Group named " + groupName + " found!", Instance);
                return null;
            }


            AudioClip clip = soundName == "random" ? group.GetRandomClip() : group.GetClip(soundName);

            if (clip == null)
            {
                Debug.LogWarning("[Phonic] No Clip named " + groupName + " found!", group);
                return null;
            }


            var source = Instance.GetChannel();
            if (source == null)
            {
                //Debug.LogWarning("Null source!", Instance);
                //Maybe warn if no channels available?
                return null;
            }


            //TODO:  Determine how heavy setting default every time is
            //ApplyOptions(source, DefaultOptions);
            DefaultOptions.Apply(source);
            ApplyOptions(source, options);

            source.clip = clip;

            source.Play();

            return source;
        }

        public static AudioSource Play(string soundPath, Options options)
        {
            if (Instance == null)
            {
                Debug.LogWarning("[Phonic] Not initialized!");
                return null;
            }


            if (soundPath == "" || soundPath == null)
            {
                return null;
            }
            string[] chunks = soundPath.Split('/');
            string groupName = chunks[0].ToLower();
            string soundName = chunks[1].ToLower();


            var group = groups[groupName];
            if (group == null)
            {
                Debug.LogWarning("[Phonic] No Group named " + groupName + " found!", Instance);
                return null;
            }


            AudioClip clip = soundName == "random" ? group.GetRandomClip() : group.GetClip(soundName);

            if (clip == null)
            {
                Debug.LogWarning("[Phonic] No Clip named " + groupName + " found!", group);
                return null;
            }


            var source = Instance.GetChannel();
            if (source == null)
            {
                //Debug.LogWarning("Null source!", Instance);
                //Maybe warn if no channels available?
                return null;
            }


            //TODO:  Determine how heavy setting default every time is
            DefaultOptions.Apply(source);
            options.Apply(source);

            source.clip = clip;

            source.Play();

            return source;
        }

        static void ApplyOptions(AudioSource source, PhonicOption[] options)
        {
            foreach (var o in options)
            {
                switch (o.type)
                {
                    case OptionType.Volume:
                        source.volume = (float)o.value;
                        break;
                    case OptionType.Position:
                        source.transform.position = (Vector3)o.value;
                        break;
                    case OptionType.Pitch:
                        source.pitch = (float)o.value;
                        break;
                    case OptionType.PanStereo:
                        source.panStereo = (float)o.value;
                        break;
                    case OptionType.SpatialBlend:
                        source.spatialBlend = (float)o.value;
                        break;
                    case OptionType.Output:
                        source.outputAudioMixerGroup = (AudioMixerGroup)o.value;
                        break;
                    case OptionType.DopplerLevel:
                        source.dopplerLevel = (float)o.value;
                        break;
                    case OptionType.Spread:
                        source.spread = (float)o.value;
                        break;
                    case OptionType.RolloffMode:
                        source.rolloffMode = (AudioRolloffMode)o.value;
                        break;
                    case OptionType.MinDistance:
                        source.minDistance = (float)o.value;
                        break;
                    case OptionType.MaxDistance:
                        source.maxDistance = (float)o.value;
                        break;
                }
            }
        }


        //options
        public static PhonicOption Position(Vector3 position)
        {
            return new PhonicOption(OptionType.Position, position);
        }

        public static PhonicOption Volume(float volume)
        {
            return new PhonicOption(OptionType.Volume, volume);
        }

        public static PhonicOption Pitch(float pitch)
        {
            return new PhonicOption(OptionType.Pitch, pitch);
        }

        public static PhonicOption Pitch(float min, float max)
        {
            return new PhonicOption(OptionType.Pitch, Random.Range(min, max));
        }

        public static PhonicOption StereoPan(float pan)
        {
            return new PhonicOption(OptionType.PanStereo, pan);
        }

        public static PhonicOption SpatialBlend(float blend)
        {
            return new PhonicOption(OptionType.SpatialBlend, blend);
        }

        public static PhonicOption Output(AudioMixerGroup group)
        {
            return new PhonicOption(OptionType.Output, group);
        }

        public static PhonicOption DopplerLevel(float doppler)
        {
            return new PhonicOption(OptionType.DopplerLevel, doppler);
        }

        public static PhonicOption Spread(float spread)
        {
            return new PhonicOption(OptionType.Spread, spread);
        }

        public static PhonicOption RolloffMode(AudioRolloffMode mode)
        {
            return new PhonicOption(OptionType.RolloffMode, mode);
        }

        public static PhonicOption MinDistance(float distance)
        {
            return new PhonicOption(OptionType.MinDistance, distance);
        }

        public static PhonicOption MaxDistance(float distance)
        {
            return new PhonicOption(OptionType.MaxDistance, distance);
        }


        //instance
        AudioSource[] channels;
        bool initialized;

        void OnEnable()
        {
            Instance = this;

        }

        void Awake()
        {
            Initialize();
        }

        void Initialize()
        {
            if (initialized)
                return;

            channels = new AudioSource[maxChannels];

            for (int i = 0; i < maxChannels; i++)
            {
                channels[i] = new GameObject("Channel " + i).AddComponent<AudioSource>();
                channels[i].transform.parent = transform;
            }

            initialized = true;
        }

        void Cleanup()
        {
            foreach (var c in channels)
            {
                Destroy(c.gameObject);
            }

            initialized = false;
        }

        AudioSource GetChannel()
        {
            return channels.FirstOrDefault(c => !c.isPlaying);
        }


    }
}
