#!/usr/bin/env python
import pandas as pd
import sys

from Main.MainArguments import MainArguments
from Main.Parameter import Parameter
from Model import MolecularScorer
from Model.ModelBuilder import ModelBuilder
from Utils import FilenameGenerator

example_parameters = """
-spectrum /home/yli/project/identification/benchmark_data/casmi_2016/spectrum_neg/test-001.mgf
-mol /home/yli/project/identification/benchmark_data/casmi_2016/candidate/test-001.txt
-model /d/test/model/neg
-out_file /d/test/score-001.txt
-threads 8
-ion 0
"""


def main():
    deal_with_arguments()

    print('Start Reading mol information.')
    mol_info = MolecularScorer.get_mol_info(Parameter.mol)
    spec_real = MolecularScorer.get_spectrum_info(Parameter.spectrum)

    for info in mol_info:
        info['spec'] = spec_real

    print('Start processing mol information.')
    model = ModelBuilder.load_from_file(FilenameGenerator.merged_peak_model_info(Parameter.model),
                                        load_training_data=False)

    annotated_info, error_info = MolecularScorer.annotate_spectra(mol_info)
    extracted_info = MolecularScorer.extract_info(annotated_info, model)

    MolecularScorer.score_with_peak_model(extracted_info, model)

    wanted_info = {
        'name': extracted_info['name'] + [x['name'] for x in error_info],
        'score': extracted_info['peak_score'] + [0.] * len(error_info),
        'identifier': extracted_info['smiles'] + [x['identifier'] for x in error_info],
    }

    df = pd.DataFrame.from_dict(wanted_info)

    MolecularScorer.output_result(df, Parameter.output_file)
    return


def deal_with_arguments():
    parser = MainArguments(description='')

    parser.add_argument('-spectrum', required=True, type=str, dest='spectrum',
                        default='', help='Set input spectrum file information.')

    parser.add_argument('-mol', required=True, type=str, dest='mol',
                        default='', help='Set candidate molecules file information.')

    parser.parse_args()


if __name__ == '__main__':
    main()
