# coding:utf-8
from tools_hjh.Tools import cat, echo, rm
import os
import shutil
from tools_hjh import Tools
from tools_hjh.Log import Log

date = Tools.locatdate()
log = Log('E:/MyFiles/MyPy/log/skyrim/' + date + '.log')


def main():
    mods = []
    # f_同步不同modlist的排序()
    f_把库中指定MOD全部mklink到指定路径(mods, mode='a')
    # f_把mod改名()
    # f_删除modlist中不存在的mod()
    # f_根据modlist把MOD重新分组送进文件夹()
    return


def f_根据modlist把MOD重新分组送进文件夹():
    root_path = r'E:\MyGames\SkyrimSE_MOD'
    
    mod_paths = []
    for mod_path in os.listdir(r'E:\MyGames\SkyrimSE_MOD'):
        if mod_path.startswith('mods_'):
            mod_paths.append(mod_path)
    
    modlist = cat(root_path + '\profiles\\' + '01_正常模式' + '\modlist.txt')
    lines = modlist.split('\n')
    lines.reverse()
    for line in lines:
        line = line.strip()
        if line.startswith('-') or line.startswith('+'):
            if line.endswith('_separator'):
                group_name = line.replace('_separator', '')[1:]
                continue
            else:
                mod_name = line[1:]
                for mod_path in mod_paths:
                    if mod_name in os.listdir(root_path + '\\' + mod_path):
                        src_path = root_path + '\\' + mod_path
                        dst_path = root_path + '\mods_' + group_name
                        if src_path != dst_path:
                            try:
                                Tools.mkdir(dst_path)
                            except:
                                pass
                            src_mod_path = src_path + '\\' + mod_name
                            dst_mod_path = dst_path + '\\' + mod_name
                            Tools.move_dir_for_windows(src_mod_path, dst_mod_path)
                            log.info(src_mod_path, dst_mod_path)
                        break
            # print(group_name, mod_name)


def f_删除modlist中不存在的mod():
    root_path = r'E:\MyGames\SkyrimSE_MOD'
    modlist = cat(root_path + '\profiles\\' + '01_正常模式' + '\modlist.txt')
    used_mods = []
    for line in modlist.split('\n'):
        line = line.strip()
        if len(line) > 0:
            if line[0] != '#' and not line.endswith('_separator'):
                used_mods.append(line[1:])
                
    src_paths = []
    for wjj in os.listdir(root_path):
        if wjj.startswith('mods_'):
            src_path = root_path + '\\' + wjj
            src_paths.append(src_path)
    
    for src_path in src_paths:
        for src_mod in os.listdir(src_path):
            if src_mod not in used_mods:
                log.info(src_path + '\\' + src_mod)
                rm(src_path + '\\' + src_mod)

            
def f_把库中指定MOD全部mklink到指定路径(mods=[], mode='a'): 
    root_path = r'E:\MyGames\SkyrimSE_MOD'
    need_root_path = root_path + r'\mods'
    need_root_path = 'E:\MyGames\SkyrimSE_MOD\mods'
    exists_mods = os.listdir(need_root_path)
    
    src_paths = os.listdir(root_path)

    for wjj in src_paths:
        if wjj.startswith('mods_'):
            src_path = root_path + '\\' + wjj
            for src_mod in os.listdir(src_path):
                need_flag = False
                if len(mods) > 0 and src_mod in mods:
                    need_flag = True
                elif len(mods) == 0:
                    need_flag = True
                else:
                    need_flag = False
                if need_flag:
                    if mode == 'a':
                        if src_mod not in exists_mods:
                            src_mod_path = src_path + '\\' + src_mod
                            need_mod_path = need_root_path + '\\' + src_mod
                            mklink_cmd = 'mklink /d "' + need_mod_path + '" "' + src_mod_path + '"'
                            del_cmd = 'rd /S /Q "' + need_mod_path + '"'
                            log.info(del_cmd)
                            mess = Tools.run_for_windows(del_cmd)
                            if '系统找不到指定的文件' not in mess:
                                log.info(mess)
                            log.info(mklink_cmd)
                            mess = Tools.run_for_windows(mklink_cmd)
                            log.info(mess)
                    else:
                        src_mod_path = src_path + '\\' + src_mod
                        need_mod_path = need_root_path + '\\' + src_mod
                        mklink_cmd = 'mklink /d "' + need_mod_path + '" "' + src_mod_path + '"'
                        del_cmd = 'rd /S /Q "' + need_mod_path + '"'
                        log.info(del_cmd)
                        mess = Tools.run_for_windows(del_cmd)
                        if '系统找不到指定的文件' not in mess:
                            log.info(mess)
                        log.info(mklink_cmd)
                        mess = Tools.run_for_windows(mklink_cmd)
                        log.info(mess)

                    
def f_删除库中空MOD():
    src_paths = []
    # src_paths.append(r'E:\MyGames\SkyrimSE_MOD\mods_自选')
    src_paths.append(r'E:\MyGames\SkyrimSE_MOD\mods_绝伦X5')
    src_paths.append(r'E:\MyGames\SkyrimSE_MOD\mods_季梓虞Y4')

    for src_path in src_paths:
        for src_mod in os.listdir(src_path):
            mod_path = src_path + '\\' + src_mod
            if len(os.listdir(mod_path)) == 0:
                os.rmdir(mod_path)
                print(mod_path)
            else:
                if len(os.listdir(mod_path)) == 1:
                    if os.listdir(mod_path)[0] == 'meta.ini':
                        rm(mod_path)
                        print(mod_path)

                
def f_把mod改名():
    root_path = r'E:\MyGames\SkyrimSE_MOD'
    modlist_s = []
    for profiles in os.listdir(root_path + r'\profiles'):
        modlist_path = root_path + r'\profiles' + r'\\' + profiles + r'\modlist.txt'
        modlist = cat(modlist_path)
        modlist_new = ''
        for line in modlist.split('\n'):
            line = line.strip()
            if len(line) > 0:
                modlist_new = modlist_new + line + '\n'
        modlist_s.append([modlist_path, modlist_new])
    
    mods = []
    mods.append(("爱丽西弗美化 Moolgogi Elisif", "爱丽西弗美化 Moolgogi's Elisif"))
    mods.append(("AAAAA", "BBBBB"))
    mods.append(("AAAAA", "BBBBB"))
    mods.append(("AAAAA", "BBBBB"))
    mods.append(("AAAAA", "BBBBB"))
    # mods.append(("AAAAA", "BBBBB"))
    
    src_paths = []
    for wjj in os.listdir(root_path):
        if wjj.startswith('mods_'):
            src_paths.append(root_path + r'\\' + wjj)
    
    for mod in mods:
        src_mod = mod[0]
        dst_mod = mod[1]
        
        for src_path in src_paths:
            if src_mod in os.listdir(src_path):
                need_del_mod_link = root_path + '\mods\\' + src_mod
                need_mk_mod_link = root_path + '\mods\\' + dst_mod
                src_mod_path = src_path + '\\' + src_mod
                dst_mod_path = src_path + '\\' + dst_mod
                shutil.move(src_mod_path, dst_mod_path)
                
                for i in range(0, len(modlist_s)):
                    modlist_s[i][1] = modlist_s[i][1].replace(src_mod, dst_mod)
                    
                mklink_cmd = 'mklink /d "' + need_mk_mod_link + '" "' + dst_mod_path + '"'
                del_cmd = 'rd /S /Q "' + need_del_mod_link + '"'
                log.info(del_cmd)
                mess = Tools.run_for_windows(del_cmd)
                if '系统找不到指定的文件' not in mess:
                    log.info(mess)
                log.info(mklink_cmd)
                mess = Tools.run_for_windows(mklink_cmd)
                log.info(mess)
                break
    
    for i in range(0, len(modlist_s)):
        echo(modlist_s[i][1], modlist_s[i][0], 'w')


def f_删除A文件夹中B已存在的文件():
    apath = r'E:\MyGames\SkyrimSE_MOD\mods_自选\BS 实验室'
    bpath = r'E:\MyGames\SkyrimSE_MOD\mods_自选\BS 基本'
    
    bfps = []
    for one in os.walk(bpath):
        if len(one[1]) == 0:
            for f in one[2]:
                fp = one[0] + '\\' + f
                fp = fp.replace(bpath, '')
                bfps.append(fp)
    
    for one in os.walk(apath):
        if len(one[1]) == 0:
            for f in one[2]:
                fp = one[0] + '\\' + f
                fp_ = fp.replace(apath, '')
                if fp_ in bfps:
                    rm(fp)
                    log.info(fp)


def f_删除空文件夹():
    src_path = r'E:\MyGames\SkyrimSE_MOD\mods_自选\BS 实验室'
    for src_mod in os.listdir(src_path):
        mod_path = src_path + '\\' + src_mod
        if len(os.listdir(mod_path)) == 0:
            os.rmdir(mod_path)
            log.info(mod_path)
        else:
            if len(os.listdir(mod_path)) == 1:
                if os.listdir(mod_path)[0] == 'meta.ini':
                    rm(mod_path)
                    log.info(mod_path)

                    
def f_同步不同modlist的排序():
    root_path = r'E:\MyGames\SkyrimSE_MOD'
    base_profiles = '正常模式'
    src_file = root_path + '\profiles\\' + base_profiles + r'\modlist.txt'
    src_mods = []
    for line in cat(src_file).split('\n'):
        src_mods.append(line[1:])
    
    dst_files = []
    for profile in os.listdir(root_path + r'\profiles'):
        if profile != base_profiles:
            dst_files.append(root_path + '\profiles\\' + profile + r'\modlist.txt')

    for dst_file in dst_files:
        name_flags = {}
        for line in cat(dst_file).split('\n'):
            if len(line.strip()) > 0:
                name = line[1:]
                flag = line[0]
                name_flags[name] = flag
        rs = ''
        # print(name_flags)
        for mod in src_mods:
            if len(mod.strip()) > 0:
                rs = rs + name_flags[mod.replace('DLC: ', 'DLC：')] + mod + '\n'
        echo(rs, dst_file, 'w')


if __name__ == '__main__':
    main()
