from utils.db_handling.db_access import get_db_object_for_dbtype_and_version
from utils.vars import MAP_FILE_BASENAME

import gzip

def get_make_dbcan_map_input_files(w):
    db_obj = get_db_object_for_dbtype_and_version("dbcan", w.db_version)
    return db_obj.get_map_resource_file(relative=True)

def create_dbcan_map(tsv_in, map_out):
    with open(tsv_in, "r") as handle, gzip.open(map_out, "wt") as map_handle:
        map_handle.write("CAZyDB family ID\tdescription\n")
        # drop header
        handle.readline()
        for line in handle:
            fields = line.strip().split("\t")
            if line.startswith("#") or len(fields) != 2:
                continue
            map_handle.write(fields[0].strip() + "\t" + fields[1].strip() + "\n")

rule make_dbcan_map:
    input:
        get_make_dbcan_map_input_files
    output:
        "dbcan/{db_version}/processed/"+MAP_FILE_BASENAME+".map.gz",
    message:
        "generating map {output[0]}"
    benchmark:
        "dbcan/{db_version}/"+MAP_FILE_BASENAME+".map.gz.benchmark.txt"
    resources:
        mem_mb=400
    version:
        "0.1"
    run:
        create_dbcan_map(input[0], output[0])
