import pandas as pd
import datetime


def gen_single_patch(antenna):
    result_str = f'// {antenna["Part Showname"]}\n// Range: '
    range_raw = antenna["Range Raw"]
    if range_raw >= 299792458 * 86400 * 365:
        range_str, range_unit = range_raw / (299792458 * 86400 * 365), ' light years'
    elif range_raw >= 149597871000:
        range_str, range_unit = range_raw / 149597871000, 'AU'
    elif range_raw >= 1000000000:
        range_str, range_unit = range_raw / 1000000000, ' million km'
    else:
        range_str, range_unit = round(range_raw / 1000), 'km'
    range_str = str(round(range_str, 3))
    idle_power = str(round(antenna["idle power watt"], 2))
    cost = int(antenna["Cost"]) if pd.notna(antenna["Cost"]) else None
    entry_cost = int(antenna["Entry Cost"]) if pd.notna(antenna["Entry Cost"]) else None
    speed = antenna["Speed"]
    transmit_power = str(round(antenna["transmitting power watt"], 2))
    result_str += (f'{range_str}{range_unit}     Angle: {antenna["Angle"]}     Idle Power: {idle_power}'
                   f'w     Transmitting Power: {transmit_power}w'
                   f'     Speed: {speed}Mbps\n')
    result_str += f'@PART[{antenna["Part"]}]:FINAL\n{"{"}\n'
    if pd.notna(antenna["Rescalefactor"]):
        result_str += f'    %rescaleFactor = {antenna["Rescalefactor"]}\n'
    if pd.notna(antenna["Tech"]):
        result_str += f'    %TechRequired = {antenna["Tech"]}\n'
    result_str += f'    %title = {antenna["Part Showname"]}\n'
    if antenna.get('Description') and pd.notna(antenna['Description']):
        description_str = antenna['Description']
        if 'Rated for' not in description_str:
            description_str += f' Rated for {speed}Mbps @{range_str}{range_unit}.'
        result_str += f'    @description = {description_str}\n'
    else:
        description_str = f'Rated for {speed}Mbps @{range_str}{range_unit}.'
        result_str += f'    %description ^= :$: {description_str}:\n'
    if cost:
        result_str += f'    %cost = {cost}\n'
    if entry_cost:
        result_str += f'    %entryCost = {entry_cost}\n'
    if antenna['mass']:
        result_str += f'    %mass = {antenna["mass"]}\n'

    if pd.notnull(antenna['Tweakscale']) and antenna['Tweakscale'] != 'Free':
        result_str += ('    %MODULE[TweakScale]\n    {\n        %type = stack\n' +
                       f'        %defaultScale = {antenna["Tweakscale"]}' + '\n    }\n')
    elif antenna['Tweakscale'] == 'Free':
        result_str += '    %MODULE[TweakScale]\n    {\n        %type = free\n    }\n'

    result_str += '    %MODULE[ModuleSPUPassive] {}\n'

    result_str += '    @MODULE[ModuleRTAntenna]\n    {\n'
    result_str += f'        @EnergyCost = {antenna["idle power"]}\n        @Mode1DishRange = {antenna["Range Raw"]}\n'
    if int(antenna['Angle']) != 360:
        result_str += f'        %DishAngle = {antenna["Angle"]}\n'
    if int(antenna['Is Deployable']) == 1:
        result_str += '        %MaxQ = 6000\n'
    result_str += '        %TRANSMITTER\n        {\n            %PacketInterval = 1\n'
    result_str += (f'            %PacketSize = {speed}\n'
                   f'            %PacketResourceCost = {antenna["transmitting power"]}\n')
    result_str += '        }\n    }\n'
    if pd.notnull(antenna['Is Feeder']) and antenna['Is Feeder']:
        result_str += ("    %MODULE[ModuleAntennaFeed]\n    {\n"
                       "        %FeedTransformName = AntennaFeedVector\n        %FeedScale = 1\n    }\n")
    result_str += '}\n\n'

    # print(result_str)
    return result_str


if __name__ == '__main__':
    path = 'D://OneDrive//文档//KSP Engine Tweak Chart.xlsx'
    excel_content = pd.read_excel(path, sheet_name='Communication')
    full_dict = {}
    for key, content in excel_content.iterrows():
        if content['Part'] == 'Spacecraft':
            continue
        title = content['Part']
        if content['Source'] not in full_dict:
            full_dict[content['Source']] = (f'// Modified {datetime.datetime.now().strftime("%Y-%m-%d")}\n'
                                            f'// Auto Modification\n\n')
        try:
            full_dict[content['Source']] += gen_single_patch(dict(content))
        except TypeError as e:
            continue
    for key, content in full_dict.items():
        print(f'{key}: \n{full_dict[key]}')
    print('done')
