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

public class SvnReleatedEditorWindow : EditorWindow
{
    public class SvnUrlInfo {
        public string url;
        public int revision;
    }
    public string assetPath = null;
    public int revision = -1;
    public List<SvnUrlInfo> svnUrlInfos;
    static readonly List<string> supportedExtensions = new(){".png",".mp3",".ogg"};
    [MenuItem("Assets/关联/关联文件")]
    static void FindRelated() {
        string assetPath = AssetDatabase.GetAssetPath(Selection.activeObject);
        if (assetPath != null) { 
            Debug.Log(assetPath);
            if (supportedExtensions.Contains(Path.GetExtension(assetPath)))
            {
                string fullPath = Path.Combine(Application.dataPath, "..", assetPath);
                string assetUrl = SvnUtil.getUrl(fullPath);
                Debug.Log(assetUrl);
                string rootUrl = "https://10.3.254.33/repos/hongen_read";
                string url = $"http://10.2.40.166:28008/get_related_svn_urls?url={assetUrl}&root={rootUrl}";
                Debug.Log(url);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                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);

                SvnReleatedEditorWindow win = (SvnReleatedEditorWindow)EditorWindow.GetWindow<SvnReleatedEditorWindow>();
                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("错误",$"查找关联文件只支持{string.Join('/',supportedExtensions)}","好的");
            }
        }
    }

    public void Init() {
    }
    Vector2 scrollPos = Vector2.zero;
    void OnGUI() {
        GUILayout.Label($"不知道Assets下的{string.Join('/',supportedExtensions)}从哪里来的？通过关联文件查找");
        GUILayout.Label($"{assetPath} @ {revision} 相关的文件:");
        scrollPos = GUILayout.BeginScrollView(scrollPos);
        int maxRevision = svnUrlInfos.Max(info => info.revision);
        foreach (SvnUrlInfo info in this.svnUrlInfos) {
            GUILayout.BeginHorizontal();
            if (info.revision == maxRevision )
            {
                if (info.revision == revision) {
                    if (GUILayout.Button("当前资源", GUILayout.Width(100)))
                    {
                    }
                }
                else if (info.revision > revision) {
                    GUIStyle style = new(GUI.skin.button);
                    style.normal.textColor = Color.yellow;
                    style.hover.textColor = Color.yellow;
                    style.active.textColor = Color.yellow;
                    if (GUILayout.Button("替换最新", style, GUILayout.Width(100))) {
                        string dstFile = Path.GetFullPath(Path.Combine(Application.dataPath, "..", assetPath));
                        string args = $"export --force \"{info.url}\" \"{dstFile}\"";
                        ExecCmd("svn", args);
                    }
                }
            }
            else { 
                if (GUILayout.Button("替换旧版", GUILayout.Width(100)))
                {
                    string dstFile = Path.GetFullPath(Path.Combine(Application.dataPath,"..",assetPath));
                    string args = $"export --force \"{info.url}\" \"{dstFile}\"";
                    ExecCmd("svn",args);
                }
            }
            if (GUILayout.Button("svn查看",GUILayout.Width(100))) {
                string args = $"/command:log /path:\"{info.url}\"";
                ExecCmd(GetTortoiseProc(),args);
            }
            GUIStyle style1 = new(GUI.skin.button);
            style1.alignment = TextAnchor.MiddleLeft;
            if (GUILayout.Button($"[{info.revision}] {info.url}",style1,GUILayout.Width(Screen.width * 0.6f))) {
                Debug.Log(info.url);
                if (File.Exists(GetTortoiseProc()))
                {
                    string[] splits = info.url.Split(new char[] { '/'});
                    List<string> list = splits.ToList(); 
                    list.RemoveAt(splits.Length - 1);
                    string url = string.Join("/", list);
                    Debug.Log(url);
                    ExecCmd(GetTortoiseProc(),$"/command:repobrowser /path:\"{url}\"");
                }
            }
            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);
    }
}
