from utils.databases.superclasses.database_superclasses import Database
import re
import os


class HmmDatabase(Database):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def get_hmmlib_file(self, *args, **kwargs):
        f = self._config["files"]['hmm_lib']
        path = self.join_with_db_path(f, *args, **kwargs)
        return path

    @staticmethod
    def iter_hmmlib(hmmlib):
        with open(hmmlib, "r") as handle:
            entry = {}
            skip = False
            for line in handle:
                line = line.strip()
                if line == "//":
                    yield entry
                    entry = {}
                    skip = False
                    continue
                elif skip or line == "":
                    continue
                if line.startswith("HMM "):
                    skip = True
                elif 'VERSION' not in entry:
                    entry['VERSION'] = line
                else:
                    fields = line.split(" ")
                    entry[fields[0]] = " ".join(fields[1:]).strip()

    def uniquify_names(self, tmpfile):
        keys = set()
        pattern = re.compile("(NAME +)(.*)")
        with open(self.get_hmmlib_file(), "r") as inhandle, open(tmpfile, "w") as outhandle:
            for line in inhandle:
                match = pattern.match(line)
                if match:
                    name = match.group(2).rstrip()
                    i = 0
                    while name in keys:
                        i += 1
                        name = match.group(2).rstrip() + "_" + str(i)
                    keys.add(name)
                    line = match.group(1) + name + "\n"
                outhandle.write(line)
        os.remove(self.get_hmmlib_file())
        os.rename(tmpfile, self.get_hmmlib_file())
