##
## CPCantalapiedra 2020

import os

from ...common import HMMSTAT
from ...utils import colorify

##
def generate_idmap(dbpath):
    if dbpath.endswith(".h3f"):
        dbpath = dbpath.replace(".h3f", "")
    cmd = """%s %s | grep -v '#' | sed '/^$/d' | awk '{print $1" "$2}' > %s""" %(HMMSTAT, dbpath, dbpath+'.idmap')
    print(colorify(cmd, "cyan"))
    print(('Generating idmap in '+dbpath+'.idmap'))
    return os.system(cmd) == 0

##
def load_idmap_idx(idmap_file):
    idmap_idx = {}

    # print(colorify("Reading idmap %s" % idmap_file, color='lblue'))
    for _lnum, _line in enumerate(open(idmap_file)):
        if not _line.strip():
            continue
        try:
            _seqid, _seqname = map(str, _line.strip().split(' '))
        except ValueError:
            if _lnum == 0:
                # idmap generated by esl_reformat has info line at beginning
                continue  
            else:
                raise
        _seqid = int(_seqid)
        idmap_idx[_seqid] = [_seqname]
    # print(str(len(idmap_idx)) + " names loaded")

    return idmap_idx

## END
