from typing import OrderedDict


def LoadMixturesTxt(fname, mix_type):
    """
    Load mixture composition
    INPUT: tab-delimited text file
    mol_name_1  mol_name_2  first_component_ratio  second_component_ratio
    mol_name_1  mol_name_3  first_component_ratio  second_component_ratio
    ...
    NOTE: number of components can be any
    OUTPUT:
    { "mol_name_1_(ratio_1)+mol_name_2_(ratio_2)":
        {'names': ["mol_name_1", "mol_name_2"], 'ratios': [ratio_1, ratio_2]},
      "mol_name_1_(ratio_1)+mol_name_3_(ratio_2)":
        {'names': ["mol_name_1", "mol_name_3"], 'ratios': [ratio_1, ratio_2]},
      ...
    }
    OUTPUT EXAMPLE:
    { 'P-Ser-Ser_(1.0)+E-37_(1.0)': {'names': ['P-Ser-Ser', 'E-37'], 'ratios': [1.0, 1.0]},
      'K-Arg-Ser_(1.0)+MS-7_(1.0)': {'names': ['K-Arg-Ser', 'MS-7'], 'ratios': [1.0, 1.0]},
      'K-Ala-Glu_(1.0)+E-21_(1.0)': {'names': ['K-Ala-Glu', 'E-21'], 'ratios': [1.0, 1.0]} }
    """
    d = OrderedDict()

    if mix_type == 'abs':
        abs_ratio = True
    else:
        abs_ratio = False

    f = open(fname, 'rt')

    while True:
        line = f.readline()
        if not line: break
        tmp = line.strip().split('\t')
        mix_num = len(tmp) // 2
        mol_names = tmp[:mix_num]
        mol_ratios = list(map(float, tmp[(len(tmp) // 2):]))
        if not abs_ratio:
            mol_ratios = [v / sum(mol_ratios) for v in mol_ratios]
        mol_ratios = [round(v, 4) for v in mol_ratios]
        mix_name = '+'.join([mol_names[i] + '_(' + str(mol_ratios[i]) + ')' for i in range(mix_num)])
        d[mix_name] = {'names': mol_names, 'ratios': mol_ratios}
    return d