import pandas as pd

propellant_dict = {
    'Hydrolox': """            PROPELLANT
            {
                name = LqdHydrogen
                ratio = 0.7276
                DrawGauge = true
            }
            PROPELLANT
            {
                name = LqdOxygen
                ratio = 0.2724
            }""",
    'Methalox': """            PROPELLANT
            {
                name = LqdMethane
                ratio = 0.4137
                DrawGauge = true
            }
            PROPELLANT
            {
                name = LqdOxygen
                ratio = 0.5863
            }""",
    'Kerolox': """            PROPELLANT
            {
                name = Kerosene
                ratio = 37.694087
                DrawGauge = True
            }
            PROPELLANT
            {
                name = LqdOxygen
                ratio = 62.305913
            }""",
    'UDMH/NTO': """            PROPELLANT
            {
                name = UDMH
                ratio = 0.4977
                DrawGauge = True
            }
            PROPELLANT
            {
                name = NTO
                ratio = 0.5023
            }""",
    'MMH/NTO': """            PROPELLANT
            {
                name = MMH
                ratio = 0.4990
                DrawGauge = True
            }
            PROPELLANT
            {
                name = NTO
                ratio = 0.5010
            }""",
    'Aerozine/NTO': """            PROPELLANT
            {
                name = Aerozine50
                ratio = 0.455
                DrawGauge = true
            }
            PROPELLANT
            {
                name = NTO
                ratio = 0.545
            }""",
    'Hydrazine': """            PROPELLANT
            {
                name = Hydrazine
                ratio = 1.0
                DrawGauge = true
            }"""
}


class Engine:
    def __init__(self, title, name=''):
        self.title = title
        self.name = name if name else None
        self.config_list = []

    def add_config(self, config):
        self.config_list.append(config)

    def __str__(self):
        return self.title

    def gen_engine_patch(self):
        cost = min([config['Price KD'] for config in self.config_list])
        cycle_dict = {'SCC': 'Staged Combustion Cycle', 'FFSCC': 'Full-Flow Stage Combustion Cycle',
                      'Gas Generator': 'Gas Generator', 'Expander': 'Expander Cycle'}
        cycle = cycle_dict.get(self.config_list[0]['Cycle'], self.config_list[0]['Cycle'])
        classification = 'Lower Stage Engine' if self.config_list[0]['SL-ISP'] > 240 else 'Upper Stage Engine'
        base_mass = self.config_list[0]['Mass']
        engine_config = ''
        for config in self.config_list:
            propellant = propellant_dict[config['Fuel Type']]
            note = config.get('Config Note')
            pressure_flag = True if config['Cycle'] == 'Pressure Fed' else False
            engine_config += f"        CONFIG\n{'        {'}\n            name = {config['Config Name']}\n"
            if not pd.notnull(note):
                note = ''
            if note:
                note += ' ' if note.endswith('.') or note.endswith('. ') else '. '
            engine_config += f"            description = {config['Config Name']} version of {self.title}. {note}"
            engine_config += f"TWR: {round(config['TWR'], 2)}\n" \
                             f"            minThrust = {config['Min Thrust']}\n" \
                             f"            maxThrust = {config['Max Thrust']}\n" \
                             f"            heatProduction = {config['Max Thrust'] / 100}\n" \
                             f"            massMult = {config['Mass'] / base_mass}\n" \
                             f"            ullage = {not pressure_flag}\n" \
                             f"            pressureFed = {pressure_flag}\n" \
                             f"            ignitions = {config['Ignitions']}\n" \
                             f"            cost = {config['Price KD'] - cost}\n" \
                             f"            IGNITOR_RESOURCE\n{'            {'}\n" \
                             f"                name = ElectricCharge\n" \
                             f"                amount = {config['Min Thrust'] / 500}\n{'            }'}\n" \
                             f"            atmosphereCurve\n{'            {'}\n" \
                             f"                key = 0 {config['Vac-ISP']}\n" \
                             f"                key = 1 {config['SL-ISP']}\n" \
                             f"{'            }'}\n{propellant}\n{'        }'}\n"

        tvc = self.config_list[0]['TVC']
        engine_patch = f"// {self.title}\n// {cycle} {classification}\n" \
                       f"// Base: {self.config_list[0]['Config Name']}  ISP:{self.config_list[0]['SL-ISP']}-" \
                       f"{self.config_list[0]['Vac-ISP']} Thrust:{self.config_list[0]['Min Thrust']}-" \
                       f"{self.config_list[0]['Max Thrust']}  mass:{base_mass}    " \
                       f"TWR:{round(self.config_list[0]['TWR'], 2)}   Ignitions: {self.config_list[0]['Ignitions']}\n" \
                       f"@PART[{self.name}]:Final\n{'{'}\n" \
                       f"    %title = {self.title}\n" \
                       f"    %entryCost = {self.config_list[0]['entry Cost']}\n" \
                       f"    %cost = {cost}\n" \
                       f"    @mass = {base_mass}\n" \
                       f"    %TechRequired = {self.config_list[0]['TechRequired']}\n" \
                       f"    %MODULE[TweakScale]\n{'    {'}\n" \
                       f"        %type = stack\n" \
                       f"        %defaultScale = {self.config_list[0]['Size']}\n{'    }'}\n" \
                       f"    @MODULE[ModuleEngines*]\n{'    {'}\n        @name = ModuleEnginesRF\n{'    }'}\n"
        if pd.notna(tvc):
            engine_patch += f"    @MODULE[ModuleGimbal*]\n{'    {'}\n        @gimbalRange = {tvc}\n" \
                            f"{'    }'}\n"
        engine_patch += f"    MODULE\n{'    {'}\n        name = ModuleEngineConfigs\n        type = ModuleEngines\n" \
                        f"        configuration = {self.config_list[0]['Config Name']}\n" \
                        f"        origMass = {base_mass}\n{engine_config}{'    }'}\n{'}'}\n"
        print(engine_patch)


if __name__ == '__main__':
    path = 'D://OneDrive//文档//KSP Engine Tweak Chart.xlsx'
    excel_content = pd.read_excel(path, sheet_name='work area')
    full_dict = {}
    for key, content in excel_content.iterrows():
        title = content['Engine']
        if title not in full_dict:
            full_dict[title] = Engine(title, content['Name'])
        full_dict[title].add_config(dict(content))

    for title in full_dict:
        full_dict[title].gen_engine_patch()
    print('done')

