import copy
import re
import os


class KSPPart:
    def __init__(self, cfg_path):
        self.cfg_path = cfg_path
        self.attributes = {}

        self.load_cfg()

    def load_cfg(self):
        file = open(self.cfg_path, 'r', encoding='utf-8')
        content = file.readlines()
        file.close()

        quote_stack, attrubute_name, attrubute_name = [], '', []

        return


def parse_cfg_content(content_list):
    content_list = [line.split('//')[0].strip() for line in content_list]
    content_stack = []

    tmp_list = []

    for i, line in enumerate(content_list):
        if not line:
            continue
        line = line.replace('\ufeff', '')
        if '=' in line:
            content_stack.append((line.split('=')[0].replace(' ', ''), line.split('=')[1].replace(' ', '')))
        else:
            content_stack.append(line)
        if '{' in line and not line.startswith('!') and not line.startswith('%'):
            content_stack.pop()
            content_stack.append('{')
        if '}' in line and not line.startswith('!') and not line.startswith('%'):
            try:
                while content_stack[-1] != '{':
                    tmp_list.append(content_stack.pop())
            except:
                raise ValueError
            tmp_list.append(content_stack.pop())
            tmp_list.reverse()
            tmp_list.pop()
            try:
                tmp_list.pop(0)
            except:
                print(tmp_list)
                return {}, {}

            module_name = content_stack.pop()
            content_stack.append({module_name: copy.deepcopy(tmp_list)})
            tmp_list = []

    part_dict = {}
    mm_list = []
    tmp_result = get_attribute(content_stack)

    for key, value in tmp_result.items():
        if key.upper() == 'PART':
            for item in value:
                if item.get('name'):
                    part_dict[item.get('name')] = item
                else:
                    raise TypeError
        elif value:
            mm_list.append({key: value})

    return part_dict, mm_list


def get_attribute(attribute_list):
    result_dict = {}
    for content in attribute_list:
        if isinstance(content, tuple):
            result_dict[content[0]] = content[1]
            continue
        if isinstance(content, str):
            if 'modification' in result_dict:
                result_dict['modification'].append(content)
            else:
                result_dict['modification'] = [content]
            continue
        if not isinstance(content, dict):
            print(f'Error: {content}')
        classification = list(content.items())[0][0]
        if classification not in result_dict:
            result_dict[classification] = [get_attribute(content[classification])]
        else:
            result_dict[classification].append(get_attribute(content[classification]))

    return result_dict


def get_cfg_files(file_path):
    result_list = []
    for filepath, dirnames, filenames in os.walk(file_path):
        for filename in filenames:
            if filename.endswith('.cfg'):
                result_list.append(os.path.join(filepath, filename))
    return result_list


def load_part_cfg(file_path):
    result_database = {}
    part_cfg_file_list = get_cfg_files(file_path)
    for cfg_path in part_cfg_file_list:
        file = open(cfg_path, 'r', encoding='utf-8')
        content = file.readlines()
        file.close()
        result_database.update(parse_cfg_content(content)[0])
    return result_database


def load_mm_cfg(file_path):
    result_database = []
    part_cfg_file_list = get_cfg_files(file_path)
    for cfg_path in part_cfg_file_list:
        file = open(cfg_path, 'r', encoding='utf-8')
        content = file.readlines()
        file.close()
        result_database.append(parse_cfg_content(content)[1])
    return result_database


if __name__ == '__main__':

    part_cfg_database = load_part_cfg("D:\\My Coding Project\\KIU-Pack\\KIU\KIU_Chinese_Launch_Vehicle_pack\\Parts")
    mm_database = load_mm_cfg("D:\\My Coding Project\\KIU-Pack\\KIU\KIU_Chinese_Launch_Vehicle_pack\\Compatibility"
                              "\\RealFuels")

    # for item in mm_database:
    #     for line in item:
    #         for part, modification in line.items():
    #             print(part, modification)

    part_flag = '@PART[KCLV_YZ3Engine]:NEEDS[RealFuels]:Final'
    modification = [{'@mass': '0.03', '@maxTemp': '2000', '@MODULE[ModuleEngines*]': [{'@name': 'ModuleEnginesRF'}], 'MODULE': [{'name': 'ModuleEngineConfigs', 'type': 'ModuleEngines', 'configuration': 'YZ3Engine_MMH/NTO', 'origMass': '0.03', 'CONFIG': [{'name': 'YZ3Engine_MMH/NTO', 'description': '5000NEnginerunningonMMH/NTO.Itiscapableofin-flightrestartandhasthrottlingcapability.', 'minThrust': '1.5', 'maxThrust': '5', 'heatProduction': '25', 'massMult': '1.0', 'ullage': 'False', 'pressureFed': 'True', 'ignitions': '35', 'IGNITOR_RESOURCE': [{'name': 'ElectricCharge', 'amount': '0.1'}], 'PROPELLANT': [{'name': 'MMH', 'ratio': '0.4990', 'DrawGauge': 'True'}, {'name': 'NTO', 'ratio': '0.5010'}], 'atmosphereCurve': [{'key': '190'}]}, {'name': 'YZ3Engine_Hydrazine', 'description': '5000NEnginerunningonHydrazine.Itissignificantlylessefficientyetweightless.', 'minThrust': '1', 'maxThrust': '4', 'heatProduction': '25', 'massMult': '0.8', 'ullage': 'False', 'pressureFed': 'True', 'ignitions': '0', 'IGNITOR_RESOURCE': [{'name': 'ElectricCharge', 'amount': '0.1'}], 'PROPELLANT': [{'name': 'Hydrazine', 'ratio': '1.0', 'DrawGauge': 'true'}], 'atmosphereCurve': [{'key': '1120'}]}, {'name': 'KZ-0125-I', 'description': 'KF-0125-IisanimaginaryvariantoftheYuanzheng-35000NEngine.IthasanimprovedISPandhigherthrust.YoushouldconsiderthisasaCheat.', 'minThrust': '1.5', 'maxThrust': '12.5', 'heatProduction': '25', 'massMult': '1.5', 'ullage': 'False', 'pressureFed': 'True', 'ignitions': '50', 'IGNITOR_RESOURCE': [{'name': 'ElectricCharge', 'amount': '0.1'}], 'PROPELLANT': [{'name': 'MMH', 'ratio': '0.4990', 'DrawGauge': 'True'}, {'name': 'NTO', 'ratio': '0.5010'}], 'atmosphereCurve': [{'key': '190'}]}]}]}]
    part_name = re.search(r'@PART\[.+?]', part_flag)[0].replace('@PART[', '').replace(']', '')
    part_item = part_cfg_database.get(part_name)
    if not part_item:
        raise ValueError

    print('done')
