#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""stress test connection pool in a multiprocessing environment

$ ./connpool-stress-test ../data/random-vars.gz

On 0.4.4, this reliably fails within 10 seconds when using a local database.
With 0.4.5a4.post0, it runs until terminated (several runs of at least two minutes).

https://github.com/biocommons/hgvs/issues/321/
"""

from __future__ import absolute_import, division, print_function, unicode_literals

import gzip
import logging
import random
import threading
import sys

from hgvs.exceptions import HGVSError
import hgvs.assemblymapper
import hgvs.dataproviders.uta
import hgvs.parser
import hgvs.variantmapper
import hgvs.validator

logging.basicConfig(level=logging.DEBUG)
_logger = logging.getLogger(__name__)

if __name__ == "__main__":
    hp = hgvs.parser.Parser()
    hdp = hgvs.dataproviders.uta.connect(pooling=True)
    am = hgvs.assemblymapper.AssemblyMapper(hdp, assembly_name='GRCh37', alt_aln_method='splign')

    keep_going = True

    fn = sys.argv[1]
    with gzip.open(fn, "rt") as fh:
        hset = [l.strip() for l in fh]
    _logger.info("read {n} variants from {fn}".format(n=len(hset), fn=fn))

    def workworkwork(hp, am, h):
        v = hp.parse_hgvs_variant(h)
        if v.type == "g":
            tvars = [am.g_to_c(v, tx) for tx in am.relevant_transcripts(v) if tx.startswith("NM")]
            _logger.info("{v} -> {n} transcripts".format(v=v, n=len(tvars)))
        elif v.type == "c":
            gv = am.c_to_g(v)
            _logger.info("{v} -> {gv}".format(v=v, gv=gv))
        elif v.type == "n":
            gv = am.n_to_g(v)
            _logger.info("{v} -> {gv}".format(v=v, gv=gv))
        return None

    def worker():
        global keep_going
        while keep_going:
            hgvs = random.choice(hset)
            try:
                workworkwork(hp, am, hgvs)
            except HGVSError as e:
                _logger.info("{h} raised {e}".format(h=hgvs, e=e))
            except Exception as e:
                _logger.error("{h} raised {e}".format(h=hgvs, e=e))
                keep_going = False

    for i in range(5):
        t = threading.Thread(target=worker)
        t.start()
