from utils.search_result_parsing import ProteomicSearchResultParser


def get_proteomic_search_result(w):
    supported_input_file_keys = ['search_result', 'report', 'mpa_report', 'mpa_multisample', 'generic_table']
    if 'search_result' in config['input']:
        proteomic_search_result_file = config['input']['search_result']
    elif 'report' in config['input']:
        proteomic_search_result_file = config['input']['report']
    elif 'mpa_report' in config['input']:
        proteomic_search_result_file = config['input']['mpa_report']
    elif 'mpa_multisample' in config['input']:
        proteomic_search_result_file = config['input']['mpa_multisample']
    elif 'generic_table' in config['input']:
        proteomic_search_result_file = config['input']['generic_table']
    elif 'pd_xml' in config['input']:
        raise NotImplementedError("Proteome Discoverer xml result files are no longer supported." + \
                                  "Please use mzIdentML or Proteome Discoverer xlsx files instead.")
    else:
        raise ValueError("Can not parse input section of provided config. One of the following keys is required:\n"
                         f"\t{supported_input_file_keys}"
                         "Input section of provided config:"
                         f"{config['input']}")
    return proteomic_search_result_file


rule parse_search_result_into_protein_groups_sql_db:
    input:
        get_proteomic_search_result
    output:
        'pgs/protein_groups_db.sql'
    params:
        search_result_style=config['input']['report_style'],
        decoy_regex=config['decoy_regex'],
        required_sample_descriptors=lambda w: [sample_name
                                               for sample_group in config['sample_groups'].values()
                                               for sample_name in sample_group] if ('sample_groups' in config) else []
    run:
        ProteomicSearchResultParser(
            result_table=input[0],
            style=params.search_result_style,
            out_file=output[0],
            decoy_regex=params.decoy_regex,
            required_sample_descriptors=params.required_sample_descriptors
        ).create_protein_groups_db()