import copy
import os
import re

from pathlib import Path


def cal_fuel_density(fuel_type):
    if fuel_type == 'kerolox':
        fuel_density = kerosene['density'] * 0.3487 + lox['density'] * 0.6513
    elif fuel_type == 'methalox':
        fuel_density = lqdmethane['density'] * 0.4137 + lox['density'] * 0.5863
    elif fuel_type == 'hydrolox':
        fuel_density = lh2['density'] * 0.7276 + lox['density'] * 0.2724
    elif fuel_type == 'MMH/NTO':
        fuel_density = common_resources_dict['MMH']['density'] * 0.499 + common_resources_dict['NTO']['density'] * 0.501
    else:
        raise TypeError
    return fuel_density


def load_common_resources(file_path):
    file = open(file_path, 'r', encoding='utf-8')
    content = file.readlines()
    file.close()

    result_dict = {}

    new_content_list = []

    for line in content:
        if line.startswith('//') or not line or not line.strip():
            continue
        new_content_list.append(line)

    new_content = ''.join(new_content_list)

    resource_list = new_content.split('RESOURCE_DEFINITION\n')
    for resource in resource_list:
        if not resource:
            continue
        name = re.search(r'name = .+', resource)[0].replace('name = ', '')
        density = re.search(r'density = .+', resource)[0].replace('density = ', '')
        try:
            unit_cost = float(re.search(r'unitCost = .+', resource)[0].replace('unitCost = ', ''))
        except ValueError:
            unit_cost = re.search(r'unitCost = .+', resource)[0].replace('unitCost = ', '')
            unit_cost = float(unit_cost.split(' //')[0].replace(' ', ''))
        try:
            density = float(density) * 1000
        except ValueError:
            density = density.split(' //')[0].replace(' ', '')
            density = float(density) * 1000
        result_dict[name] = {'density': density, 'unitCost': unit_cost}
    return result_dict


def cal_tank_volume(fuel_mass, fuel_type):
    fuel_density = cal_fuel_density(fuel_type)
    return fuel_mass / fuel_density


def cal_fuel_mass(fuel_dict):
    fuel_mass = 0
    for fuel, volume in fuel_dict.items():
        fuel_mass += common_resources_dict[fuel]['density'] * volume
    return fuel_mass


def cal_fuel_mass_based_on_tank_volume(fuel_type, tank_volume):
    fuel_density = cal_fuel_density(fuel_type)
    fuel_mass = tank_volume * fuel_density
    return fuel_mass


if __name__ == '__main__':
    path = os.path.join('data', 'CommonResources.cfg')
    common_resources_dict = load_common_resources(path)
    lqdmethane = common_resources_dict['LqdMethane']
    kerosene = common_resources_dict['Kerosene']
    lox = common_resources_dict['LqdOxygen']
    lh2 = common_resources_dict['LqdHydrogen']
    # fuel_density = kerosene['density'] * 0.3487 + lox['density'] * 0.6513

    # fuel_density = lqdmethane['density'] * 0.4137 + lox['density'] * 0.5863
    # required_fuel_mass = 173800
    # result_fuel_tank_volume = cal_tank_volume(1666600, 'hydrolox')
    # print(cal_tank_volume(60000, 'hydrolox'))
    print(cal_tank_volume(339000, 'kerolox'))
    print(cal_fuel_mass({'Kerosene': 48345.13, 'LqdOxygen': 90298.77}))
    print(cal_fuel_mass_based_on_tank_volume('kerolox', 108000))
    print(cal_fuel_mass({'LqdHydrogen': 54802.1756419623, 'LqdOxygen': 20516.9222581005}))
    print(cal_fuel_density('MMH/NTO'), cal_fuel_density('methalox'))
    print('done')
