using CommonUtil;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Unity.EditorCoroutines.Editor;

using System.Net.Http;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;

public class SvnAudioSearchEditorWindow : EditorWindow
{
    public class AudioInfo {
        public string url;
        public int revision;
        public string sep_list;
    }
    public class DelayDestroy { 
        public float delay;
        public float time;
        public GameObject go;
        public bool timeover = false;
    }
    List<AudioInfo> audioInfos = new();
    List<DelayDestroy> delayDestroyList = new();
    DelayDestroy currDelayDestroy = null;
    [MenuItem("Tool/search/AudioSearch")]
    static void Open() {
        SvnAudioSearchEditorWindow win = (SvnAudioSearchEditorWindow)EditorWindow.GetWindow<SvnAudioSearchEditorWindow>();
        win.Show();
    }
    public void Init() {
    }
    async void Query(string words) {
        isSearching = true;
        using HttpClient client = new();
        client.BaseAddress = new Uri("http://10.2.40.166:28008");
        try
        {
            string param = $"query_audio?index=audiowords-hongen_read&words={words}";
            HttpResponseMessage response = await client.GetAsync(param);
            response.EnsureSuccessStatusCode();
            string responseData = await response.Content.ReadAsStringAsync();
            Debug.Log(responseData);
            audioInfos = JsonConvert.DeserializeObject<List<AudioInfo>>(responseData);
            isSearching = false;
            Repaint();
        }
        catch (HttpRequestException e)
        {
            Debug.LogError($"Request error: {e.Message}");
            isSearching = false;
            Repaint();
        }
    }
    IEnumerator PlayAudio(string file)
    {
        AudioType type = AudioType.UNKNOWN;
        if (file.EndsWith(".mp3"))
        {
            type = AudioType.MPEG;
        }
        else if (file.EndsWith(".ogg"))
        {
            type = AudioType.OGGVORBIS;
        }
        UnityWebRequest req = UnityWebRequestMultimedia.GetAudioClip($"file://{file}", type);
        yield return req.SendWebRequest();

        if (req.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError($"Error downloading audio file: {req.error}");
        }
        else
        {
            AudioClip audioClip = DownloadHandlerAudioClip.GetContent(req);
            PlayClipAtPoint(audioClip);
            //DestroyImmediate(audioClip);
        }
    }

    public void PlayClipAtPoint(AudioClip clip)
    {
        if(currDelayDestroy != null)
        {
            DestroyImmediate(currDelayDestroy.go);
            currDelayDestroy = null;
        }
        GameObject gameObject = new("One shot audio")
        {
            hideFlags = HideFlags.HideAndDontSave
        };
        AudioSource audioSource = (AudioSource)gameObject.AddComponent(typeof(AudioSource));
        audioSource.clip = clip;
        audioSource.spatialBlend = 1f;
        audioSource.volume = 1f;
        audioSource.Play();
        currDelayDestroy = new DelayDestroy()
        {
            delay = clip.length,
            time = Time.realtimeSinceStartup,
            go = gameObject,
        };
        delayDestroyList.Add(currDelayDestroy);
    }
    string searchText = "";
    Vector2 scrollPos = Vector2.zero;
    bool isSearching = false;
    private void OnGUI()
    {
        scrollPos = GUILayout.BeginScrollView(scrollPos);
        int len = searchText.Length;
        searchText = EditorGUILayout.TextField(searchText);
        GUILayout.Label("ÇëÊäÈëÎÄ×ÖËÑË÷ÒôÆµ");
        if(searchText.Length != len ) {
            Query(searchText);
        }
        if (isSearching)
        {
            GUILayout.Label("ÕýÔÚËÑË÷....");
        }
        else { 
            foreach( AudioInfo audioInfo in audioInfos )
            {
                GUILayout.Label(audioInfo.sep_list);
                GUILayout.Label($"{audioInfo.url}@{audioInfo.revision}");
                GUILayout.BeginHorizontal();
                if (GUILayout.Button("PLAY", GUILayout.Width(200))) {
                    string filename = Path.GetFileName(audioInfo.url);
                    string file = Path.Combine(Environment.GetEnvironmentVariable("TEMP"),filename);
                    string args = $"export --force \"{audioInfo.url}@{audioInfo.revision}\" \"{file}\"";
                    CmdUtil.Cmd("svn",args);
                    Debug.Log(file);
                    this.StartCoroutine(PlayAudio(file));
                }
                if (GUILayout.Button("COPY URL", GUILayout.Width(200)))
                {
                    GUIUtility.systemCopyBuffer = audioInfo.url;
                }
                GUILayout.EndHorizontal();
                //GUILayout.Label("-----------------------------------");
                EditorGUILayout.Separator();
            }
        }
        GUILayout.EndScrollView();
    }
    private void Update()
    {
        float time = Time.realtimeSinceStartup;
        foreach (DelayDestroy delay in this.delayDestroyList) {
            if (time - delay.time > delay.delay) {
                delay.timeover = true;
                DestroyImmediate(delay.go);
            }
        }
        this.delayDestroyList.RemoveAll(delay => delay.timeover);
    }
    private void OnDisable()
    {
        if (currDelayDestroy != null) {
            DestroyImmediate(currDelayDestroy.go);
            currDelayDestroy = null;
        }
    }
}
