import pandas as pd
from src.PostgresSQL.databaseHandler import DatabaseHandler


def process_excel():
    path = 'C://Users//26549//OneDrive//文档//KSP Engine Tweak Chart.xlsx'
    excel_content = pd.read_excel(path)
    data_list = []
    for row, content in excel_content.iterrows():
        if isinstance(content['Vac-ISP'], str) and '-' in content['Vac-ISP']:
            content['SL-ISP'], content['Vac-ISP'] = float(content['Vac-ISP'].split('-')[0]), float(
                content['Vac-ISP'].split('-')[1])
        else:
            content['SL-ISP'] = content['Vac-ISP']
        data_list.append(dict(content))

    df = pd.DataFrame(data_list, columns=[item for item in data_list[0]])
    df.to_excel('data//KSP Engine Tweak Chart_NEW.xlsx')


def upload_to_database(database_config):
    path = 'C://Users//26549//OneDrive//文档//KSP Engine Tweak Chart.xlsx'
    excel_content = pd.read_excel(path, keep_default_na=False)

    table_structure = dict(excel_content.loc[1])
    data_content_list = [dict(values) for _key, values in excel_content.iterrows()]
    for key, values in table_structure.items():
        if str(values) in ('nan', 'nat'):
            table_structure[key] = 'TEXT'
        elif isinstance(values, float):
            table_structure[key] = 'FLOAT4'
        else:
            table_structure[key] = 'TEXT'
    handler = DatabaseHandler(database_config)

    handler.create_table(table_structure, 'Engine_Data', force_create=True)
    handler.insert_into_table('Engine_Data', data_content_list)

    handler.close()


if __name__ == '__main__':
    # process_excel()
    config = {'database': 'KSP', 'user': 'postgres', 'password': 'Armor17909', 'host': '127.0.0.1', 'port': '5432'}
    upload_to_database(config)



    print('done')
