using CommonUtil;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;
using Unity.EditorCoroutines.Editor;
using System;
using System.Security.Policy;

public class SvnDocSearchEditorWindow : EditorWindow
{
    public class DocInfo {
        public string id;
        public string url;
        public int revision;
        public string sep_list;
        public string brief;
    }
    public class DelayDestroy { 
        public float delay;
        public float time;
        public GameObject go;
        public bool timeover = false;
    }
    List<DocInfo> docInfos = new();
    string server_url = "http://10.2.40.166:28008";
    [MenuItem("Tool/search/DocSearch")]
    static void Open() {
        SvnDocSearchEditorWindow win = (SvnDocSearchEditorWindow)EditorWindow.GetWindow<SvnDocSearchEditorWindow>();
        win.Show();
    }
    public void Init() {
    }
    async void Query(string words) {
        isSearching = true;
        using HttpClient client = new();
        client.BaseAddress = new System.Uri(server_url );
        try
        {
            string param = $"query_docx?index=word_content-hongen_read&words={words}";
            HttpResponseMessage response = await client.GetAsync(param);
            response.EnsureSuccessStatusCode();
            string responseData = await response.Content.ReadAsStringAsync();
            Debug.Log(responseData);
            docInfos = JsonConvert.DeserializeObject<List<DocInfo>>(responseData);
            foreach (DocInfo docInfo in docInfos)
            {
                docInfo.brief = docInfo.sep_list[..Math.Min(docInfo.sep_list.Length, 100)];
            }
            isSearching = false;
            Repaint();
        }
        catch (HttpRequestException e)
        {
            Debug.LogError($"Request error: {e.Message}");
            isSearching = false;
            Repaint();
        }
    }
    async void GetContent(string id) {
        using HttpClient client = new();
        client.BaseAddress = new System.Uri(server_url);
        try
        {
            string param = $"docx_content?index=word_content-hongen_read&id={id}";
            HttpResponseMessage response = await client.GetAsync(param);
            response.EnsureSuccessStatusCode();
            string responseData = await response.Content.ReadAsStringAsync();
            Debug.Log(responseData);
            textAreaContent = responseData;
            Repaint();
        }
        catch (HttpRequestException e)
        {
            Debug.LogError($"Request error: {e.Message}");
            Repaint();
        }
    }
    string searchText = "";
    Vector2 scrollPosList = Vector2.zero;
    Vector2 scrollPosSelected = Vector2.zero;
    bool isSearching = false;
    DocInfo selectedDocInfo = null;
    string textAreaContent = "";
    private void OnGUI()
    {
        float scrollPercent = 0.7f;
        scrollPosList = GUILayout.BeginScrollView(scrollPosList,GUILayout.Height(this.position.height * scrollPercent));
        int len = searchText.Length;
        searchText = EditorGUILayout.TextField(searchText);
        GUILayout.Label("请输入文字搜索docx文档");
        if(searchText.Length != len ) {
            Query(searchText);
        }
        if (isSearching)
        {
            GUILayout.Label("正在搜索....");
        }
        else { 
            foreach(DocInfo docInfo in docInfos)
            {
                GUILayout.Label(docInfo.brief);
                GUILayout.Label($"{docInfo.url}@{docInfo.revision}");
                GUILayout.BeginHorizontal();
                if (GUILayout.Button("SELECT", GUILayout.Width(200)))
                {
                    selectedDocInfo = docInfo;
                    //textAreaContent = docInfo.sep_list; 
                    GetContent(docInfo.id);
                }
                if (GUILayout.Button("OPEN", GUILayout.Width(200))) {
                    string filename = Path.GetFileName(docInfo.url);
                    string file = Path.Combine(System.Environment.GetEnvironmentVariable("TEMP"),filename);
                    string args = $"export --force \"{docInfo.url}@{docInfo.revision}\" \"{file}\"";
                    CmdUtil.Cmd("svn",args);
                    Debug.Log(file);
                    System.Diagnostics.Process.Start(file);
                }
                if (GUILayout.Button("COPY URL", GUILayout.Width(200)))
                {
                    GUIUtility.systemCopyBuffer = docInfo.url;
                }
                GUILayout.EndHorizontal();
                //GUILayout.Label("-----------------------------------");
                EditorGUILayout.Separator();
            }
        }
        GUILayout.EndScrollView();
        if(selectedDocInfo != null)
        {
            scrollPosSelected = GUILayout.BeginScrollView(scrollPosSelected,GUILayout.Height(this.position.height * (1f - scrollPercent)));
            textAreaContent = GUILayout.TextArea(textAreaContent, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
            GUILayout.EndScrollView();
        }
    }
    private void OnDisable()
    {
    }
}
