using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using CommonUtil;
using Newtonsoft.Json;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;

public class SvnUpdateIncomeEditorWindow : EditorWindow
{
    public class ReplaceInfo { 
        public string url;
        public int revision;
    }
    public class SvnUrlInfo {
        public string url;
        public int revision;
        public ReplaceInfo replace;
    }
    public string assetPath = null;
    public int revision = -1;
    public List<SvnUrlInfo> svnUrlInfos;
    static readonly List<string> supportedExtensions = new(){".png",".mp3",".ogg"};
    static readonly string rootUrl = "https://10.3.254.33/repos/hongen_read";
    [MenuItem("Assets/关联/目录内可更新关联文件")]
    static void FindRelated() {
        if (Selection.assetGUIDs.Length == 0) return;
        string assetPath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);
        if (assetPath != null)
        {
            Debug.Log(assetPath);
            if (AssetDatabase.IsValidFolder(assetPath))
            {
                string fullPath = Path.GetFullPath(Path.Combine(Application.dataPath, "..", assetPath));
                string assetUrl = SvnUtil.getUrl(fullPath);
                if (assetUrl != "")
                {
                    Debug.Log(assetUrl);
                    string url = $"http://10.2.40.166:28008/get_update_income_svn_urls?url={assetUrl}&root={rootUrl}";
                    Debug.Log(url);
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.Timeout = 1800 * 1000;
                    request.Method = "GET";
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    Stream myResponseStream = response.GetResponseStream();
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                    string retString = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponseStream.Close();
                    Debug.Log(retString);

                    SvnUpdateIncomeEditorWindow win = (SvnUpdateIncomeEditorWindow)EditorWindow.GetWindow<SvnUpdateIncomeEditorWindow>();
                    win.assetPath = assetPath;
                    int.TryParse(SvnUtil.getRevision(assetPath), out win.revision);
                    win.svnUrlInfos = JsonConvert.DeserializeObject<List<SvnUrlInfo>>(retString);
                    Debug.Log(win.svnUrlInfos);
                    win.Init();
                }
                else { 
                    EditorUtility.DisplayDialog("错误", "不是svn目录", "好的");
                }
            }
            else
            {
                EditorUtility.DisplayDialog("错误", "必须是目录", "好的");
            }
        }
        else { 
            EditorUtility.DisplayDialog("错误", "未选中目录", "好的");
        }
    }

    public void Init() {
    }
    Vector2 scrollPos = Vector2.zero;
    void OnGUI() {
        GUILayout.Label($"不知道Assets下的{string.Join('/',supportedExtensions)}从哪里来的？通过关联文件查找");
        GUILayout.Label($"{assetPath} @ {revision} 相关的文件:");
        scrollPos = GUILayout.BeginScrollView(scrollPos);
        foreach (SvnUrlInfo info in this.svnUrlInfos) {
            GUILayout.BeginHorizontal();
            string relative = Path.GetRelativePath(rootUrl, info.url);
            string relativeIncome = Path.GetRelativePath(rootUrl, info.replace.url);
            GUILayout.Button("替换",GUILayout.Width(100));
            GUILayout.Label($"{relative}@{info.revision} <- {relativeIncome}@{info.replace.revision}");
            GUILayout.EndHorizontal();
        }
        GUILayout.EndScrollView();
    }
    string GetTortoiseProc() { 
        string tortoiseSvnProc = RegistryUtil.GetRegistryStringValue("SOFTWARE\\TortoiseSVN", "ProcPath", "", RegistryView._64);
        return tortoiseSvnProc;
    }
    void ExecCmd(string proc,string args) {
        Debug.Log($"{proc} {args}");
        System.Diagnostics.Process process = new System.Diagnostics.Process();
        process.StartInfo.FileName = proc;
        process.StartInfo.Arguments = args;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.Start();
        process.WaitForExit();
        Debug.Log(process.StandardOutput);
        Debug.Log(process.StandardError);
    }
}
