import hashlib
import os
from utils.lca_determination.determine_lca import create_lca


def md5sum(filename):
    data = open(filename, 'rb').read()
    return hashlib.md5(data).hexdigest()


def test_democratic_lca_on_map(tmpdir):
    path_abs = os.path.abspath('tests/integration_tests/weighted_lca/resources/')
    task_map = path_abs + '/job_resources/fun_annot_by_hmmer-latest_on_pfams.v33.1.task0.map'
    pg_db = path_abs + '/job_resources/protein_groups_db.sql'
    lca_out = tmpdir + '/fun_annot_by_hmmer-latest_on_pfams.v33.1.task0.lca'
    lca_support_out = tmpdir + '/fun_annot_by_hmmer-latest_on_pfams.v33.1.task0.lca_support'
    result_lca = path_abs + '/expected-results/fun_annot_by_hmmer-latest_on_pfams.v33.1.task0.lca'
    result_lca_support = path_abs + '/expected-results/fun_annot_by_hmmer-latest_on_pfams.v33.1.task0.lca_support'
    threshold = 0.501
    method = 'democratic_lca'
    n_lca_levels = 5
    tax_map = None
    is_taxonomic_annotation = False
    create_lca(task_map, pg_db, lca_out, lca_support_out, method, is_taxonomic_annotation, n_lca_levels, tax_map, threshold)
    assert md5sum(result_lca) == md5sum(lca_out)
    assert md5sum(result_lca_support) == md5sum(lca_support_out)


def test_democratic_lca_on_map_with_spectra(tmpdir):
    path_abs = os.path.abspath('tests/integration_tests/weighted_lca/resources/')
    task_map = path_abs + '/job_resources_with_spectra/tax_annot_by_diamond_on_ncbi_nr.task0.008a2274598ccb4815cd004587cfb1c6.map'
    pg_db = path_abs + '/job_resources_with_spectra/protein_groups_db_with_spectra.sql'
    lca_out = tmpdir + '/tax_annot_by_diamond_on_ncbi_nr.task0.008a2274598ccb4815cd004587cfb1c6.lca'
    lca_support_out = tmpdir + '/tax_annot_by_diamond_on_ncbi_nr.task0.008a2274598ccb4815cd004587cfb1c6.lca_support'
    result_lca = path_abs + '/expected-results/tax_annot_by_diamond_on_ncbi_nr.task0.008a2274598ccb4815cd004587cfb1c6.lca'
    result_lca_support = path_abs + '/expected-results/tax_annot_by_diamond_on_ncbi_nr.task0.008a2274598ccb4815cd004587cfb1c6.lca_support'
    threshold = 0.501
    method = 'democratic_lca'
    is_taxonomic_annotation = True
    n_lca_levels = 7
    tax_map = path_abs + '/job_resources_with_spectra/taxdump.map.gz'
    create_lca(task_map, pg_db, lca_out, lca_support_out, method, is_taxonomic_annotation, n_lca_levels, tax_map, threshold)
    assert md5sum(result_lca) == md5sum(lca_out)
    assert md5sum(result_lca_support) == md5sum(lca_support_out)
