#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os, sys
import shutil
import re
from kconfiglib import Kconfig
from menuconfig import menuconfig

def mconf_set_env(argv):
    """
    Set Kconfig Env
    """
    os.environ["MENUCONFIG_STYLE"] = "default selection=fg:white,bg:blue"
    os.environ["KCONFIG_CONFIG"] = os.path.join(".bconfig")
    os.environ["KCONFIG_CONFIG_HEADER"] = "# Generated by BabyOS Configuration"
    os.environ["KCONFIG_AUTOHEADER"] = os.path.join("b_config.h")
    os.environ["CONFIG_"] = ""

def mconfig(argv):
    print(argv[0])
    
    kconf_fd = open("Kconfig", 'w+')
    kconf_list = "mainmenu " + "\"BabyOS Configuration\" \n"
    kconf_list += "source " + "\"" + argv[1] + "/core/Kconfig" + "\"" + "\n" 
    kconf_list += "source " + "\"" + argv[1] + "/hal/Kconfig" + "\"" + "\n"
    kconf_list += "source " + "\"" + argv[1] + "/mcu/Kconfig" + "\"" + "\n"
    kconf_list += "source " + "\"" + argv[1] + "/algorithm/Kconfig" + "\"" + "\n"
    kconf_list += "source " + "\"" + argv[1] + "/drivers/Kconfig" + "\"" + "\n"
    kconf_list += "source " + "\"" + argv[1] + "/modules/Kconfig" + "\"" + "\n"
    kconf_list += "source " + "\"" + argv[1] + "/thirdparty/Kconfig" + "\"" + "\n"
    kconf_list += "source " + "\"" + argv[1] + "/utils/Kconfig" + "\"" + "\n"
    kconf_list += "source " + "\"" + argv[1] + "/services/Kconfig" + "\"" + "\n"
    print(kconf_list)
    kconf_fd.write(kconf_list)
    kconf_fd.close()
    
    #parent_pid = os.getppid()
    #parent_name = psutil.Process(parent_pid).name()
    #print(psutil.Process(parent_pid).name())
    #if parent_name.find('cmd.exe') < 0:

    mconf_set_env(argv)
    kconf = Kconfig(filename="./Kconfig")
    menuconfig(kconf)
    kconf.write_autoconf()
    bconf_fd = open("b_config.h", 'r')
    bconf_data = bconf_fd.read()
    bconf_fd.close()
    print(bconf_data)

    bconf_new_data = "#ifndef __B_CONFIG_H__ \n"
    bconf_new_data += "#define __B_CONFIG_H__ \n\n\n"
    bconf_new_data += bconf_data
    bconf_new_data += "\n\n#include \"b_type.h\" \n\n"
    bconf_new_data += "#endif \n\n"
    bconf_fd = open("b_config.h", 'w')
    bconf_fd.write(bconf_new_data)
    bconf_fd.close()
    
    os.remove("Kconfig")

def find_files(dirs, des):
    source_file = []
    source_file_des = []
    for d in dirs:
        files = os.listdir(d)
        for file_name in files:
            # 检查文件扩展名是否为.c或.h
            if file_name.endswith('.c') or file_name.endswith('.h') or file_name.endswith('.inc'):
                # 构建源文件和目标文件的完整路径
                source_file.append(os.path.join(d, file_name))
                source_file_des.append(os.path.join(des, file_name))
    return source_file,source_file_des

def clear_directory(directory):
    # 获取目录中的所有文件和子目录
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        # 判断是否是文件
        if os.path.isfile(file_path):
            # 删除文件
            os.remove(file_path)
        # 如果是子目录,则递归清空子目录中的文件
        elif os.path.isdir(file_path):
            clear_directory(file_path)

def process_includes(file_path):
    with open(file_path, 'r') as f:
        content = f.read()
    # 使用正则表达式匹配所有#include语句,并去掉路径部分
    pattern = r'#include\s+"(\.\./)*(\S*/)*(.+?)"'
    content = re.sub(pattern, r'#include "\3"', content)
    with open(file_path, 'w') as f:
        f.write(content)


def cp_arm_2d_file(bos_dir):
    arm_2d_dir = bos_dir + "/thirdparty/arm-2d/"
    tmp_dir = arm_2d_dir + "bos_arm-2d/"
    if not os.path.exists(tmp_dir):
        os.makedirs(tmp_dir)
    else:
        print("bos_arm-2d exist !")
        return
    arm_2d_file_dir = [arm_2d_dir + "Helper/Source/", arm_2d_dir + "Helper/Include/",
                       arm_2d_dir + "Library/Source/", arm_2d_dir + "Library/Include/", 
                       arm_2d_dir + "examples/[template][babyos]/",
                       arm_2d_dir + "examples/common/controls/",
                       arm_2d_dir + "examples/common/asset/"]
    arm_2d_files,tmp_dir_files = find_files(arm_2d_file_dir, tmp_dir)
    for i in range(len(arm_2d_files)):
        shutil.copy2(arm_2d_files[i], tmp_dir_files[i])
        process_includes(tmp_dir_files[i])
    

if __name__ == "__main__":
    mconfig(sys.argv)
    cp_arm_2d_file(sys.argv[1])