using CommonUtil;
using UnityEngine;
using UnityEditor;
using System.IO;
using EditorUtils;
using System;
using System.Text;
using System.Text.RegularExpressions;
using iHuman.UnitySz.Framework;
using System.Collections.Generic;

public class CopyVideoToFolder{
    public static string AssetsRoot = Application.dataPath.Replace("\\", "/") + "/"; //F:/repos/ihuman-art/app/Assets/
    public static string bookRoot = "art/book";
    public static string expandArtRoot = "art/game/expand";
    public static string expandCodeRoot = "gamesrc/expand";
    public static string poetryArtRoot = "art/game/gushi";
    public static string poetryCodeRoot = "gamesrc/poetry";
    public static string monthlyArtRoot = "art/game/monthly";
    public static string monthlyCodeRoot = "gamesrc/monthly";
    public static string svnVideoRootPath = "https://10.3.254.33/repos/hongen_read/product/视频/720p";
    public static string svnSrtRootPath = "https://10.3.254.33/repos/hongen_read/product/视频/";

    [MenuItem("Assets/自定义创建/绘本/拷贝视频")]
    public static void CopyBookVideo(){
        string[] strs = Selection.assetGUIDs;
        string trunkPath = System.Environment.CurrentDirectory;
        if (strs != null)
        {
            foreach (string str in strs)
            {
                string id = GetID(str);
                if (!String.IsNullOrEmpty(id))
                {
                    bool isDirty = false;
                    // 创建目标的video path
                    string dstVideoPath = Path.Combine(trunkPath, "Assets", bookRoot, $"{id}", "video");
                    if(!Directory.Exists(dstVideoPath)){
                        Directory.CreateDirectory(dstVideoPath);
                    }
                    string[] videoNameList = {$"video_book_{id}.mp4"};
                    foreach (var videoName in videoNameList)
                    {
                        string svnVideoPath = svnVideoRootPath + $"/{videoName}";
                        bool _isCopy = _CopyOneFile(svnVideoPath, dstVideoPath + $"/{videoName}");
                        if(_isCopy){
                            isDirty = true;
                        }
                    }
                    string[] srtNameList = {$"video_book_{id}_srt.txt"};
                    foreach (var srtName in srtNameList)
                    {
                        string svnSrtFilePath = svnSrtRootPath + @$"/绘本引入/{id}" + @$"/{srtName}";
                        bool _isCopy = _CopyOneFile(svnSrtFilePath, dstVideoPath + $"/{srtName}");
                        if(_isCopy){
                            isDirty = true;
                        }
                    }
                    if(isDirty){
                        AssetDatabase.Refresh();
                        BookTool.GenBook(id);
                        Debug.Log($"book {id} copy success!");
                    }else{
                        Debug.Log($"book {id} not exist video file!");
                    }
                }
            }
        }
    }

    public static bool _CopyOneFile(string svnFilePath, string dstFilePath){
        if(!SvnUtil.isExit(svnFilePath)){
            return false;
        }
        string filePath = SvnUtil.getFile(svnFilePath);
        if(filePath != null){
            
            if(File.Exists(dstFilePath)){
                File.Delete(dstFilePath);
            }
            File.Move(filePath, dstFilePath);
            return true;
        }
        return false;
    }


    [MenuItem("Assets/自定义创建/拓环节/拷贝视频")]
    public static void CopyExpandVideo(){
        string[] strs = Selection.assetGUIDs;
        string trunkPath = System.Environment.CurrentDirectory;
        if (strs != null)
        {
            foreach (string str in strs)
            {
                string id = GetID(str);
                if (!String.IsNullOrEmpty(id))
                {
                    // 创建目标的video path
                    string dstVideoPath = Path.Combine(trunkPath, "Assets", expandArtRoot, $"expand{id}", "video");
                    if(!Directory.Exists(dstVideoPath)){
                        Directory.CreateDirectory(dstVideoPath);
                    }
                    bool isDirty = false;
                    string[] videoNameList = {$"video_expand_{id}_1.mp4", $"video_expand_{id}_2.mp4"};
                    foreach (var videoName in videoNameList)
                    {
                        string svnVideoPath = svnVideoRootPath + $"/{videoName}";
                        bool _isCopy = _CopyOneFile(svnVideoPath, dstVideoPath + $"/{videoName}");
                        if(_isCopy){
                            isDirty = true;
                        }
                    }
                    string[] srtNameList = {$"video_expand_{id}_1_srt.txt", $"video_expand_{id}_2_srt.txt"};
                    foreach (var srtName in srtNameList)
                    {
                        string svnSrtFilePath = svnSrtRootPath + @$"/每日成长/{id}" + @$"/{srtName}";
                        bool _isCopy = _CopyOneFile(svnSrtFilePath, dstVideoPath + $"/{srtName}");
                        if(_isCopy){
                            isDirty = true;
                        }
                    }
                    if(!isDirty){
                        Debug.Log($"expand {id} not exist video file!");
                        continue;
                    }
                    AssetDatabase.Refresh();
                    GenExpandVideoReslink(id);
                    Debug.Log($"expand {id} copy success!");
                }
            }
        }
    }

    public static void GenExpandVideoReslink(string id){
        string trunkPath = System.Environment.CurrentDirectory;
        // 修改reslink
        string gameCodePath = Path.Combine(trunkPath, "Assets", "gamesrc", "expand", $"expand{id}");
        if(!Directory.Exists(gameCodePath)){
            Directory.CreateDirectory(gameCodePath);
        }

        string dstVideoPath = Path.Combine(trunkPath, "Assets", expandArtRoot, $"expand{id}", "video");
        // 添加video和srt
        string[] filePaths = Directory.GetFiles(dstVideoPath, "*.*", SearchOption.AllDirectories);

        string reslinkFullPath = "Assets/" + expandCodeRoot + "/" + $"expand{id}/expand{id}reslink.asset";
        var reslink = AssetDatabase.LoadAssetAtPath<ResLinkAsset>(reslinkFullPath);
        if (reslink == null)
        {
            reslink = ScriptableObject.CreateInstance<ResLinkAsset>();
        }
        foreach (string filePath in filePaths){
            string ffilePath = filePath.Replace("\\", "/");
            string fileExtension = Path.GetExtension(filePath).ToLower();
            string fileName = Path.GetFileName(filePath).ToLower();
            string key = fileName.Substring(0, fileName.Length - fileExtension.Length);

            if (fileExtension == ".mp4" || fileExtension == ".txt"){

                string relativePath = "Assets/" + ffilePath.Replace(AssetsRoot, "");
                // Debug.Log($"filePath: {filePath} key: {key} relativePath: {relativePath}");
                UnityEngine.Object value = AssetDatabase.LoadMainAssetAtPath(relativePath);
                DeleteKey(reslink.assets, key);
                reslink.assets.Add(new ResLinkAsset.Item
                {
                    Key = key,
                    Val = value,
                });
            }
        }
        if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(reslink)))
        {

            var parent = Directory.GetParent(reslinkFullPath);
            Directory.CreateDirectory(parent.FullName);
            AssetDatabase.CreateAsset(reslink, reslinkFullPath);
        }
        ResLinkEditor.Save(reslink);
        EditorUtility.SetDirty(reslink);
        AssetDatabase.SaveAssets();
    }

    [MenuItem("Assets/自定义创建/古诗/拷贝视频")]
    public static void CopyPoetryVideo(){
        string[] strs = Selection.assetGUIDs;
        string trunkPath = System.Environment.CurrentDirectory;
        if (strs != null)
        {
            foreach (string str in strs)
            {
                string id = GetID(str);
                if (!String.IsNullOrEmpty(id))
                {
                    string[] sectionList = {"travel", "through", "sing"};
                    foreach (var section in sectionList)
                    {
                        bool isDirty = false;
                        // 创建目标的video path
                        string dstVideoPath = Path.Combine(trunkPath, "Assets", poetryArtRoot, section, $"{id}", "video");
                        if(!Directory.Exists(dstVideoPath)){
                            Directory.CreateDirectory(dstVideoPath);
                        }
                        string videoName = $"video_poetry_{section}_{id}.mp4";
                        string svnVideoPath = svnVideoRootPath + $"/{videoName}";
                        bool _isCopy = _CopyOneFile(svnVideoPath, dstVideoPath + $"/{videoName}");
                        if(_isCopy){
                            isDirty = true;
                        }
                        if(section == "travel"){
                            videoName = $"video_poetry_{section}_{id}_start.mp4";
                            svnVideoPath = svnVideoRootPath + $"/{videoName}";
                            _isCopy = _CopyOneFile(svnVideoPath, dstVideoPath + $"/{videoName}");
                            if(_isCopy){
                                isDirty = true;
                            }
                        }

                        string srtName = $"video_poetry_{section}_{id}_srt.txt";
                        string svnSrtFilePath = svnSrtRootPath + @$"/古诗/{id}" + @$"/{srtName}";
                        _isCopy = _CopyOneFile(svnSrtFilePath, dstVideoPath + $"/{srtName}");
                        if(_isCopy){
                            isDirty = true;
                        }
                        if(!isDirty){
                            Debug.Log($"poetry {id} not exist video file!");
                            continue;
                        }
                        AssetDatabase.Refresh();
                        
                        // 修改reslink
                        string gameCodePath = Path.Combine(trunkPath, "Assets", "gamesrc", "poetry", section, $"{id}");
                        if(!Directory.Exists(gameCodePath)){
                            Directory.CreateDirectory(gameCodePath);
                        }
                        // 添加video和srt
                        string[] filePaths = Directory.GetFiles(dstVideoPath, "*.*", SearchOption.AllDirectories);
                        string reslinkFullPath = "Assets/" + poetryCodeRoot + "/" + $"{section}/{id}/{section}{id}reslink.asset";
                        var reslink = AssetDatabase.LoadAssetAtPath<ResLinkAsset>(reslinkFullPath);
                        if (reslink == null)
                        {
                            reslink = ScriptableObject.CreateInstance<ResLinkAsset>();
                        }
                        foreach (string filePath in filePaths){
                            string ffilePath = filePath.Replace("\\", "/");
                            string fileExtension = Path.GetExtension(filePath).ToLower();
                            string fileName = Path.GetFileName(filePath).ToLower();
                            string key = fileName.Substring(0, fileName.Length - fileExtension.Length);

                            if (fileExtension == ".mp4" || fileExtension == ".txt"){

                                string relativePath = "Assets/" + ffilePath.Replace(AssetsRoot, "");
                                // Debug.Log($"filePath: {filePath} key: {key} relativePath: {relativePath}");
                                UnityEngine.Object value = AssetDatabase.LoadMainAssetAtPath(relativePath);
                                DeleteKey(reslink.assets, key);
                                reslink.assets.Add(new ResLinkAsset.Item
                                {
                                    Key = key,
                                    Val = value,
                                });
                            }
                        }
                        if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(reslink)))
                        {
                            var parent = Directory.GetParent(reslinkFullPath);
                            Directory.CreateDirectory(parent.FullName);
                            AssetDatabase.CreateAsset(reslink, reslinkFullPath);
                        }
                        ResLinkEditor.Save(reslink);
                        EditorUtility.SetDirty(reslink);
                        AssetDatabase.SaveAssets();
                        Debug.Log($"poetry {section} {id} copy success!");
                    }
                }
            }
        }
    }

    [MenuItem("Assets/自定义创建/古诗/删除视频")]
    public static void DeletePoetryVideo(){
        string[] strs = Selection.assetGUIDs;
        string trunkPath = System.Environment.CurrentDirectory;
        if (strs != null)
        {
            foreach (string str in strs)
            {
                string id = GetID(str);
                if (!String.IsNullOrEmpty(id))
                {
                    string[] sectionList = {"travel", "through", "sing"};
                    foreach (var section in sectionList)
                    {
                        bool isDirty = false;
                        // 创建目标的video path
                        string dstVideoPath = Path.Combine(trunkPath, "Assets", poetryArtRoot, section, $"{id}", "video");
                        if(Directory.Exists(dstVideoPath)){
                            Directory.Delete(dstVideoPath, true);
                        }
                        if(File.Exists(dstVideoPath + ".meta")){
                            File.Delete(dstVideoPath + ".meta");
                        }
                        AssetDatabase.Refresh();
                        
                        // 修改reslink
                        string gameCodePath = Path.Combine(trunkPath, "Assets", "gamesrc", "poetry", section, $"{id}");
                        if(!Directory.Exists(gameCodePath)){
                            Directory.CreateDirectory(gameCodePath);
                        }
                        string reslinkFullPath = "Assets/" + poetryCodeRoot + "/" + $"{section}/{id}/{section}{id}reslink.asset";
                        var reslink = AssetDatabase.LoadAssetAtPath<ResLinkAsset>(reslinkFullPath);
                        if (reslink == null)
                        {
                            break;
                        }

                        for (int i = reslink.assets.Count-1; i>=0; i--)
                        {
                            if (reslink.assets[i].Key.Contains("video_") || reslink.assets[i].Key.Contains("_srt"))
                            {
                                reslink.assets.Remove(reslink.assets[i]);
                            }
                        }
                        ResLinkEditor.Save(reslink);
                        EditorUtility.SetDirty(reslink);
                        AssetDatabase.SaveAssets();
                        Debug.Log($"poetry {section} {id} delete success!");
                    }
                }
            }
        }
    }
    [MenuItem("Assets/自定义创建/月课/拷贝视频")]
    public static void CopyMonthlyVideo(){
        string[] strs = Selection.assetGUIDs;
        string trunkPath = System.Environment.CurrentDirectory;
        if (strs != null)
        {
            foreach (string str in strs)
            {
                string id = GetID(str);
                if (!String.IsNullOrEmpty(id))
                {
                    string[] sectionList = {""};
                    foreach (var section in sectionList)
                    {
                        bool isDirty = false;
                        // 创建目标的video path
                        string dstVideoPath = Path.Combine(trunkPath, "Assets", monthlyArtRoot, $"monthly{id}", "video");
                        if(!Directory.Exists(dstVideoPath)){
                            Directory.CreateDirectory(dstVideoPath);
                        }
                        string videoName = $"video_month_{id}.mp4";
                        string svnVideoPath = svnVideoRootPath + $"/{videoName}";
                        bool _isCopy = _CopyOneFile(svnVideoPath, dstVideoPath + $"/{videoName}");
                        if(_isCopy){
                            isDirty = true;
                        }

                        string srtName = $"video_month_{id}_srt.txt";
                        string svnSrtFilePath = svnSrtRootPath + @$"/月课/{id}" + @$"/{srtName}";
                        _isCopy = _CopyOneFile(svnSrtFilePath, dstVideoPath + $"/{srtName}");
                        if(_isCopy){
                            isDirty = true;
                        }
                        if(!isDirty){
                            Debug.Log($"month {id} not exist video file!");
                            continue;
                        }
                        AssetDatabase.Refresh();
                        
                        // 修改reslink
                        string gameCodePath = Path.Combine(trunkPath, "Assets", "gamesrc", "monthly", $"monthly{id}");
                        if(!Directory.Exists(gameCodePath)){
                            Directory.CreateDirectory(gameCodePath);
                        }
                        // 添加video和srt
                        string[] filePaths = Directory.GetFiles(dstVideoPath, "*.*", SearchOption.AllDirectories);
                        string reslinkFullPath = "Assets/" + monthlyArtRoot + "/" + $"monthly{id}/reslink/{id}reslink.asset";
                        var reslink = AssetDatabase.LoadAssetAtPath<ResLinkAsset>(reslinkFullPath);
                        if (reslink == null)
                        {
                            reslink = ScriptableObject.CreateInstance<ResLinkAsset>();
                        }
                        foreach (string filePath in filePaths){
                            string ffilePath = filePath.Replace("\\", "/");
                            string fileExtension = Path.GetExtension(filePath).ToLower();
                            string fileName = Path.GetFileName(filePath).ToLower();
                            string key = fileName.Substring(0, fileName.Length - fileExtension.Length);

                            if (fileExtension == ".mp4" || fileExtension == ".txt"){

                                string relativePath = "Assets/" + ffilePath.Replace(AssetsRoot, "");
                                // Debug.Log($"filePath: {filePath} key: {key} relativePath: {relativePath}");
                                UnityEngine.Object value = AssetDatabase.LoadMainAssetAtPath(relativePath);
                                DeleteKey(reslink.assets, key);
                                reslink.assets.Add(new ResLinkAsset.Item
                                {
                                    Key = key,
                                    Val = value,
                                });
                            }
                        }
                        if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(reslink)))
                        {
                            var parent = Directory.GetParent(reslinkFullPath);
                            Directory.CreateDirectory(parent.FullName);
                            AssetDatabase.CreateAsset(reslink, reslinkFullPath);
                        }
                        ResLinkEditor.Save(reslink);
                        EditorUtility.SetDirty(reslink);
                        AssetDatabase.SaveAssets();
                        Debug.Log($"month {id} copy success!");
                    }
                }
            }
        }
    }

    public static void CopyWeeklyVideo()
    {
        WeeklyClassTools.CreateVideoAsset();
    }

    public static void DeleteKey(List<ResLinkAsset.Item> asset, string key){
        foreach(ResLinkAsset.Item item in asset){
            if(item.Key == key){
                //把这个key直接删除
                asset.Remove(item);
                break;
            }
        }
    }
    public static string GetID(string assetGUID)
    {
        var folderName = AssetDatabase.GUIDToAssetPath(assetGUID);
        if (!AssetDatabase.IsValidFolder(folderName))
        {
            folderName = Path.GetDirectoryName(folderName);
        }
        Match match = Regex.Match(folderName, @"\d+"); // 匹配一个或多个数字
        string id = match.Success ? match.Value : "";
        return id;
    }

}
