#!/usr/bin/env python

import argparse
import sys
import logging
import os

sys.path = [os.path.join(os.path.dirname(os.path.realpath(__file__)),'..')] + sys.path

from kgt_mlst import version

__author__ = "Malte B. Hallgren"
__version__ = version.__version__

from kgt_mlst import determine_mlst

def main():
    description = 'kgt-mlst, a mlst interepter for kmergenetyper results'

    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('-i', action="store", type=str, dest='input', nargs='+',
                        default=None, help='Input read file(s).')
    parser.add_argument('-species', action="store", type=str, dest='species',
                        default=None, help='Input species following this format: '
                                           'the first letter of the genus and the entire species, all in lowercase letters. '
                                           'Example: Escherichia coli should be ecoli. Campylobacter jejuni should be cjejuni. '
                                           'If no species is given, species identification will be run - this requires downloading the reference bacterial DB with --download_db.')
    parser.add_argument('-db_dir', action="store", type=str, dest='db_dir',
                        default=None, help='Path to where the kgt_mlst database is located.')
    parser.add_argument('-md', action="store", type=int, dest='min_depth',
                        default=5, help='Minimum depth of coverage to be considered for mlst alleles.')
    parser.add_argument('-o', action="store", type=str, dest='output', help='Output directory')
    parser.add_argument('--download_db', action="store_true", dest='download_db',
                        default=False, help='Download the kgt_mlst database.')
    parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__)

    args = parser.parse_args()

    if args.download_db:
        download_db(args)
    else:
        determine_mlst.determine_mlst(args)


def download_db(arguments):
    os.system('mkdir kgt_mlst_db')
    os.system("git clone https://bitbucket.org/genomicepidemiology/mlst_db.git kgt_mlst_db/mlst_db".format(arguments.output))
    file_list = os.listdir('kgt_mlst_db/mlst_db')
    for species in file_list:
        if os.path.exists('kgt_mlst_db/mlst_db/{0}/{0}.fsa'.format(species)):
            os.system(
                "kma index -i kgt_mlst_db/mlst_db/{0}/{0}.fsa -o kgt_mlst_db/mlst_db/{0}/{0} -m 14".format(
                    species, species))

    os.system("wget https://cge.food.dtu.dk/services/MINTyper/bac_species_db.tar.gz kgt_mlst_db/bac_species_db.tar.gz")
    os.system("tar -xvzf bac_species_db.tar.gz")
    os.system("mv bac_species_db kgt_mlst_db/bac_species_db")
    os.system("rm kgt_mlst_db/bac_species_db.tar.gz")

if __name__ == '__main__':
    main()

