# -- coding: utf-8 --
import argparse
from cmsis_svd.parser import SVDParser
import importlib
import sys
import analyzer
import pkgutil


args = None
periph_list = {}
device = None


def parse_args():
    parser = argparse.ArgumentParser()

    parser.add_argument("--port",
                        default="COM1",
                        help="Serial Port")
    parser.add_argument("--baudrate",
                        type=int,
                        default=1000000,
                        help="Baudrate")
    parser.add_argument("soc",
                        help="SoC Series, e.g. SF32LB52X")
    parser.add_argument("modules",
                        # nargs=1,
                        help="Modules need to be analyzed")

    return parser.parse_args()                        


def get_group_name(periph_name):
    group_name = None
    for peripheral in device.peripherals:
        periph_name = periph_name.upper()
        if peripheral.name == periph_name:
            group_name = peripheral._group_name
            break
    
    return group_name

def analyze(periph_name):
    periph_type = get_group_name(periph_name)
    if not periph_type:
        print(f"无效的外设: {periph_name}")
        return

    analyzer_class = None
    if device.name.upper() == "SF32LB52X":
        analyzer_db_mod = importlib.import_module('sf32lb52x.analyzer_db')
    elif device.name.upper() == "SF32LB56X":
        analyzer_db_mod = importlib.import_module('sf32lb56x.analyzer_db')
   
    # analyzer_class = analyzer_db_mod.analyzer_db.get(periph_type)
    analyzer_class = analyzer.analyzer_db.get(periph_type)

    if not analyzer_class:
        print(f"未找到{periph_name}的分析器")
        return

    periph_analyzer = analyzer_class(device, periph_name, args.port, args.baudrate)
    periph_analyzer.run()


def _main():
    global args
    global device

    args = parse_args()

    parser = SVDParser.for_xml_file(f'{args.soc}/{args.soc}.svd')
    device = parser.get_device()

    analyze(args.modules)


if __name__ == "__main__":
    _main()
