#!/usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
import os

from Bio import SeqIO
from BioSQL import BioSeqDatabase
from seqann import BioSeqAnn, gfe
from seqann.blast_cmd import get_locus


def main():
    """This is run if file is directly executed, but not if imported as
    module. Having this in a separate function  allows importing the file
    into interactive python, and still able to execute the
    function for testing"""
    parser = argparse.ArgumentParser()
    parser.add_argument("-f", "--file",
                        required=True,
                        help="input file",
                        type=str)

    parser.add_argument("-l", "--locus",
                        required=False,
                        help="HLA locus",
                        type=str)

    parser.add_argument("-k", "--kir",
                        required=False,
                        help="Bool for KIR",
                        action='store_true')

    parser.add_argument("-s", "--server",
                        required=False,
                        help="BioSQL server",
                        default=False,
                        type=bool)

    parser.add_argument("-v", "--verbose",
                        help="Option for running in verbose",
                        action='store_true')

    args = parser.parse_args()
    fasta_file = args.file
    loc = args.locus
    serv = args.server

    verbose = False
    if args.verbose:
        verbose = True

    kir = False
    if args.kir:
        kir = True

    server = None
    if serv:
        biosqldb_host = os.getenv('BIOSQLHOST', 'localhost')
        biosqldb_port = int(os.getenv('BIOSQLPORT', 3306))
        biosqldb_user = os.getenv('BIOSQLUSER', 'root')
        biosqldb_pass = os.getenv('BIOSQLPASS', '')
        biosqldb_name = os.getenv("BIOSQLDB", "bioseqdb")

        server = BioSeqDatabase.open_database(driver="pymysql",
                                              user=biosqldb_user, passwd=biosqldb_pass,
                                              host=biosqldb_host, port=biosqldb_port,
                                              db=biosqldb_name)

    seqann = BioSeqAnn(verbose=verbose, server=server, kir=kir)

    gfe_maker = gfe.GFE()
    for seq in SeqIO.parse(fasta_file, "fasta"):
        if not loc:
            loc = get_locus(seq, kir=kir, verbose=verbose,
                            refdata=seqann.refdata)

        try:
            ann = seqann.annotate(seq, loc)
        except ValueError as e:
            print("Skipping sequence: " + loc + " reason:", e)
            break

        features, gfe_name = gfe_maker.get_gfe(ann, loc)
        print('{:*^20} {:^20} {:*^20}'.format("", str(seq.description), ""))
        l = 0
        for f in ann.annotation:
            print(gfe_name, f, ann.method, str(ann.annotation[f]), sep="\t")
            l += len(ann.annotation[f])
        print("Total Length:", l)

    if serv:
        server.close()


if __name__ == '__main__':
    """The following will be run if file is executed directly,
    but not if imported as a module"""
    main()
