from utils.db_handling.db_access import get_db_object_for_dbtype_and_version
import os


def get_unzipped_hmmlib(w):
    db_obj = get_db_object_for_dbtype_and_version(w.db_type, w.db_version)
    hmmlib_file = db_obj.get_hmmlib_file(relative=True)
    # if downloaded hmmlib is gzipped, return the unzipped file created by the rule
    # gunzip_directly_downloaded_db_resource_file
    if hmmlib_file.endswith(".gz"):
        hmm_lib_basename_wo_gz = os.path.basename(os.path.splitext(hmmlib_file)[0])
        db_dir = os.path.dirname(db_obj.get_yaml(relative=True))
        hmmlib = os.path.join(db_dir, "processed", hmm_lib_basename_wo_gz) + ".unzipped"
    else:
        hmmlib = hmmlib_file
    return hmmlib

rule make_hmm_lib:
  input:
    get_unzipped_hmmlib
  output:
    "{db_type}/{db_version}/processed/hmmlib-{vers}",
    "{db_type}/{db_version}/processed/hmmlib-{vers}.h3f",
    "{db_type}/{db_version}/processed/hmmlib-{vers}.h3i",
    "{db_type}/{db_version}/processed/hmmlib-{vers}.h3m",
    "{db_type}/{db_version}/processed/hmmlib-{vers}.h3p"
  message:
    "preparing hmm db for first use: {input[0]}"
  log:
    "{db_type}/{db_version}/processed/hmmlib-{vers}.log"
  version:
    "0.12"
  conda:
    "../../envs/hmmer-{vers}.yaml"
  threads: 4
  benchmark:
    "{db_type}/{db_version}/processed/hmmlib-{vers}.h3x.benchmark.txt"
  resources:
    mem_mb=100
  params: rel_hmmlib_in=lambda w, input, output: os.path.relpath(input[0], os.path.dirname(output[0]))
  shell:
    '''
	ln -s {params.rel_hmmlib_in} {output[0]}
    hmmpress {output[0]} >> {log} 2>&1
    '''
