using System;
using System.Collections.Generic;
using UnityEngine;

namespace OCES.Audio
{
    public partial class AudioObjectConfig
    { 
        Dictionary<uint, Dictionary<int, uint>> m_switchMapping;

        internal void PreParseSwitchMappings()
        {
            this.m_switchMapping = new Dictionary<uint, Dictionary<int, uint>>();
            foreach (AudioObject audioObject in AudioObjectList())
            {
                if (audioObject.ContainerType != ContainerType.Switch) continue;
                this.m_switchMapping[audioObject.Id] = ParseSwitchMapping(audioObject);
            }
        }
        
        public AudioObject GetMappingResult(uint switchContainerId, Enum enumState)
        {
            if (!this.m_switchMapping.TryGetValue(switchContainerId, out Dictionary<int, uint> switchMapping))
                return null;
            
            return switchMapping.TryGetValue(enumState.GetHashCode(), out uint audioObjectId) ? QueryById(audioObjectId) : null;

        }

        Dictionary<int, uint> ParseSwitchMapping(AudioObject switchContainer)
        {
            Dictionary<int, uint> switchMapping = new();
            foreach (string name in switchContainer.Name)
            {
                string[] parts = name.Split(',');
                if(parts.Length != 2)
                {
                    Debug.LogWarning($"[AudioSystem] 无法解析 Switch Container {switchContainer.Id} 的映射关系！请检查表");
                    continue;
                }

                if (!int.TryParse(parts[0].Trim(), out int stateValue))
                {
                    Debug.LogWarning($"[AudioSystem] 无法解析 映射关系！请查表");
                    continue;
                }

                if (!uint.TryParse(parts[1].Trim(), out uint childId))
                {
                    Debug.LogWarning("");
                    continue;
                }
                
                switchMapping.Add(stateValue, childId);
            }
            return switchMapping;
        }
        
        internal AudioObject GetDefaultSwitchOrFallback(AudioObject switchContainer)
        {
            if (switchContainer.DefaultSwitchId == 0)
                return null;
            AudioObject defaultChildAudioObject = QueryById(switchContainer.DefaultSwitchId);
            if (defaultChildAudioObject != null) 
                return defaultChildAudioObject;
                
            Debug.LogWarning($"[AudioSystem] DefaultSwitch AudioObject {switchContainer.DefaultSwitchId} 不存在。");
            return null;
        }
    }
}
