import yaml
import sys

# 自定义Dumper类以在每个配置项之间添加空行
class MyDumper(yaml.Dumper):
    isNeedNewLine = False
    def increase_indent(self, flow=False, indentless=False):
        # 增加缩进层级
        return super().increase_indent(flow, False)

    def represent_list(self, data):
        # 自定义列表格式，确保每个列表项单独换行
        items = super().represent_list(data)
        # 在每个项之间添加空行
        for i in range(len(items) - 1):
            items.insert(2 * i + 1, yaml.ScalarNode(tag='tag:yaml.org,2002:str', value=''))  # 添加空行
            items[i * 2 + 1].style = 'block'  # 设置为块样式
        return items
    
    def write_line_break(self, data=None):
        # 在每个节点之间添加换行
        if len(self.indents) == 1:
            self.isNeedNewLine = False
        if len(self.indents) > 1 and not self.indents[-1]:  # 确保当前块的末尾
            if not self.isNeedNewLine:
                self.isNeedNewLine = True
            else:
                super().write_line_break()  # 添加换行
        super().write_line_break(data)  # 正常的行结束

    
          

class BaseConfig:
    readId = ""
    artName = ""
    artPath = ""
    srcName = ""
    srcPath = ""
    artUseLatest = True
    srcUseLatest = True
    tags = ""
    def __init__(self, readId):
        self.readId = readId
    def getArtName(self):
        return self.artName + self.readId
    def getArtPath(self):
        return self.artPath + self.readId
    def getSrcName(self):
        return self.srcName + self.readId
    def getSrcPath(self):
        return self.srcPath + self.readId
    def getTag(self):
        return [self.tags + self.readId]
    def getArtUseLastest(self):
        return self.artUseLatest
    def getSrtUseLastest(self):
        return self.srcUseLatest
    def isHaveSrc(self):
        return self.getSrcPath() != None
 
class BookConfig(BaseConfig):
    artName = "trunk/art/book/"
    artPath = "Assets/art/book/"
    tags = "book"
    def __init__(self, readId):
        super().__init__(readId)
    def getSrcPath(self):
        return None
    
class PracticeConfig(BaseConfig):
    artName = "trunk/art/game/practice/practice"
    artPath = "Assets/art/game/practice/practice"
    srcName = "trunk/dev/gamesrc/practice/practice"
    srcPath = "Assets/gamesrc/practice/practice"
    tags = "practice"
    def __init__(self, readId):
        super().__init__(readId)

class SayConfig(BaseConfig):
    artName = "trunk/art/game/say/say"
    artPath = "Assets/art/game/say/say"
    srcName = "trunk/dev/gamesrc/say/say"
    srcPath = "Assets/gamesrc/say/say"
    tags = "say"
    def __init__(self, readId):
        super().__init__(readId)

class ExpandConfig(BaseConfig):
    artName = "trunk/art/game/expand/expand"
    artPath = "Assets/art/game/expand/expand"
    srcName = "trunk/dev/gamesrc/expand/expand"
    srcPath = "Assets/gamesrc/expand/expand"
    tags = "expand"
    def __init__(self, readId):
        super().__init__(readId)

class GushiTravelConfig(BaseConfig):
    artName = "trunk/art/game/gushi/travel/"
    artPath = "Assets/art/game/gushi/travel/"
    srcName = "trunk/dev/gamesrc/poetry/travel/"
    srcPath = "Assets/gamesrc/poetry/travel/"
    tags = "gushi_travel_"
    def __init__(self, readId):
        super().__init__(readId)

class GushiThroughConfig(BaseConfig):
    artName = "trunk/art/game/gushi/through/"
    artPath = "Assets/art/game/gushi/through/"
    srcName = "trunk/dev/gamesrc/poetry/through/"
    srcPath = "Assets/gamesrc/poetry/through/"
    tags = "gushi_through_"
    def __init__(self, readId):
        super().__init__(readId)

class GushiSayConfig(BaseConfig):
    artName = "trunk/art/game/gushi/say/"
    artPath = "Assets/art/game/gushi/say/"
    srcName = "trunk/dev/gamesrc/poetry/say/"
    srcPath = "Assets/gamesrc/poetry/say/"
    tags = "gushi_say_"
    def __init__(self, readId):
        super().__init__(readId)

class GushiExerciseConfig(BaseConfig):
    artName = "trunk/art/game/gushi/exercise/exercise"
    artPath = "Assets/art/game/gushi/exercise/exercise"
    srcName = "trunk/dev/gamesrc/poetry/exercise/exercise"
    srcPath = "Assets/gamesrc/poetry/exercise/exercise"
    tags = "gushi_exercise_exercise"
    def __init__(self, readId):
        super().__init__(readId)

class GushiSingConfig(BaseConfig):
    artName = "trunk/art/game/gushi/sing/"
    artPath = "Assets/art/game/gushi/sing/"
    srcName = "trunk/dev/gamesrc/poetry/sing/"
    srcPath = "Assets/gamesrc/poetry/sing/"
    tags = "gushi_sing_"
    def __init__(self, readId):
        super().__init__(readId)

class WeeklyConfig(BaseConfig):
    artName = "trunk/art/game/weekly/weekly"
    artPath = "Assets/art/game/weekly/weekly"
    srcName = "trunk/dev/gamesrc/weekly/weekly"
    srcPath = "Assets/gamesrc/weekly/weekly"
    tags = "weekly"
    def __init__(self, readId):
        super().__init__(readId)

class MonthlyConfig(BaseConfig):
    artName = "trunk/art/game/monthly/monthly"
    artPath = "Assets/art/game/monthly/monthly"
    tags = "monthly"
    def __init__(self, readId):
        super().__init__(readId)
    def getSrcPath(self):
        return None

def openYml(path):
    repos_name_map = {}
    with open(path, 'r', encoding='utf-8') as file:
        cfg = yaml.safe_load(file)
        repos = cfg["repos"]
        for item in repos:
            repos_name_map[item["name"]] = item
    return repos_name_map, cfg

def writeYml(path, repos_cfg):
    with open(path, 'w', encoding='utf-8') as file:
        yaml.dump(repos_cfg, file, Dumper=MyDumper, default_flow_style=False, sort_keys=False)

def genYml(ymlType, ymlPath, id_list):
    readType = ymlType
    yml_path = ymlPath
    id_list = str.split(id_list, ",")
    cfg_class = BookConfig
    if readType == "book":
        cfg_class = BookConfig
    elif readType == "practice":
        cfg_class = PracticeConfig
    elif readType == "say":
        cfg_class = SayConfig
    elif readType == "expand":
        cfg_class = ExpandConfig
    elif readType == "gushi_travel":
        cfg_class = GushiTravelConfig
    elif readType == "gushi_through":
        cfg_class = GushiThroughConfig
    elif readType == "gushi_say":
        cfg_class = GushiSayConfig
    elif readType == "gushi_exercise":
        cfg_class = GushiExerciseConfig
    elif readType == "gushi_sing":
        cfg_class = GushiSingConfig
    elif readType == "weekly":
        cfg_class = WeeklyConfig
    elif readType == "monthly":
        cfg_class = MonthlyConfig
    else:
        print("you need gen yml type :%s not exist!!" % readType)
        return

    repos_name_map, origin_cfg = openYml(yml_path)
    for readId in id_list:
        readCfg = cfg_class(readId)
        # 查找一下有没有
        artName = readCfg.getArtName()
        if artName not in repos_name_map:
            print("gen %s art" % readId)
            tmpMap = {
                "name": artName,
                "path": readCfg.getArtPath(),
                "use_lastest":True,
                "tags": readCfg.getTag()
            }
            repos_name_map[artName] = tmpMap
        else:
            print("%s artPath is exist" % readId)
            pass

        if readCfg.isHaveSrc():
            name = readCfg.getSrcName()
            if name not in repos_name_map:
                print("gen %s src" % readId)
                tmpMap = {
                    "name": name,
                    "path": readCfg.getSrcPath(),
                    "use_lastest":True,
                    "tags": readCfg.getTag()
                }
                repos_name_map[name] = tmpMap
            else:
                print("%s srcPath is exist" % readId)
                pass
        else:
            print("%s dont't have src path! no need gen" % readId)
            
    sorted_repos = dict(sorted(repos_name_map.items(), key=lambda item: item[1]['name']))
    origin_cfg["repos"] = list(sorted_repos.values())
    #重新写入yml文件
    writeYml(yml_path, origin_cfg)


def main():
    # parser = argparse.ArgumentParser(description="gen yml")
    # parser.add_argument('--yml', type=str, help='yml type', required=True)
    # parser.add_argument('--ymlpath', type=str, help='yml path', required=True)
    # parser.add_argument('--idlist', type=str, help='idlist', required=True)
    # # 解析参数
    # args = parser.parse_args()

    # print(args.yml)
    # print(args.ymlpath)
    # print(args.idlist)

    # genYml(readType=args.yml, ymlPath=args.ymlpath, id_list=args.idlist)
    a1 = sys.argv[1]
    a2 = sys.argv[2]
    a3 = sys.argv[3]

    print(a1)
    print(a2)
    print(a3)

    genYml(a1, a2, a3)
if __name__ == '__main__':
    main()
