using UnityEngine;
using System.IO;

namespace chungus_awesome
{
    [KSPAddon(KSPAddon.Startup.AllGameScenes, false)]
    public class ChungusSoundBlaster : MonoBehaviour
    {
        static ChungusSoundBlaster instance;
        AudioSource source;
        const int samplerate = 48000;
        int position = 0;
        byte[] chungData;

        public void Start()
        {
            if (instance != null)
            {
                chungData = instance.chungData;
                Destroy(instance.source);
                Destroy(instance);
            }
            instance = this;

            if (chungData == null)
            {
                var clipPath = Path.Combine(KSPUtil.ApplicationRootPath, "GameData/chungus_2/untitled.raw");
                Debug.Log("clippath exists:" + File.Exists(clipPath));
                if (!File.Exists(clipPath))
                {
                    Debug.LogError("Couldnt find chungus audio.");
                    return;
                }
                chungData = File.ReadAllBytes(clipPath);
            }

            AudioClip myClip = AudioClip.Create("chungsound", chungData.Length, 1, samplerate, false, OnAudioRead, OnAudioSetPosition);
            source = gameObject.AddComponent<AudioSource>();
            source.clip = myClip;
            source.loop = true;
            source.volume = 0;
            source.Play();
        }

        void OnAudioRead(float[] data)
        {
            int count = 0;
            while (count < data.Length)
            {
                data[count] = chungData[position % chungData.Length] / 255f;
                position++;
                count++;
            }
        }
        void OnAudioSetPosition(int newPosition)
        {
            position = newPosition;
        }

        public void FixedUpdate()
        {
            CelestialBody chungsun = null;

            if (FlightGlobals.Bodies == null || FlightGlobals.Bodies.Count == 0)
            {
                Debug.LogError($"Chungus sound blaster couldnt find any bodies.", this);
                return;
            }
            foreach(var b in FlightGlobals.Bodies)
                if(b.name == "chungsun") 
                    chungsun = b;
            if(chungsun == null)
            {
                Debug.LogError("chungsun couldnt be found, even though bodies did exist.", this);
                return;
            }

            var chungpos = ScaledSpace.ScaledToLocalSpace(chungsun.position);
            //line stolen from ludi
            var campos = ScaledSpace.ScaledToLocalSpace(PlanetariumCamera.fetch.transform.position) * ScaledSpace.ScaleFactor;
            
            float dist = Mathf.Log10((float)Vector3d.Distance(campos, chungpos));
            dist -= 11;
            source.volume = Mathf.Clamp01((3 - dist) / 6) * .3f;
        }
    }
}
