#!/usr/bin/env python
import os.path
import shlex
from subprocess import Popen
import sys

import immunedb.common.config as config
from immunedb.common.models import Subject
from immunedb.util.log import logger

if __name__ == '__main__':
    parser = config.get_base_arg_parser('''Runs TIgGER to infer genotypes for
                                        subjects''')
    parser.add_argument('v_germlines', help='''FASTA file with IMGT gapped
                        V-gene germlines''')
    parser.add_argument('--changeo-export-path', default='.')
    parser.add_argument('--subject-ids', nargs='+', type=int, help='''Limit to
                        certain subjects''')
    parser.add_argument('--j-max', type=float, default=1.0, help='''[TIgGER]
                        Maximum fraction of sequences perfectly aligning to a
                        potential novel allele that are allowed to utilize to a
                        particular combination of junction length and J
                        gene''')
    parser.add_argument('--min-seqs', type=int, default=10, help='''[TIgGER]
                        Minimum number of total sequences required for the
                        samples to be considered''')
    parser.add_argument('--germline-min', type=int, default=10,
                        help='''[TIgGER] Minimum number of sequences that must
                        have a particular germline allele call for the allele
                        to be analyzed''')
    args = parser.parse_args()
    session = config.init_db(args.db_config)

    subjects = session.query(Subject)
    if args.subject_ids:
        subjects = subjects.filter(Subject.id.in_(args.subject_ids))
    for subject in subjects:
        changeo_path = '{}.changeo.tsv'.format(subject.identifier)
        if not os.path.isfile(changeo_path):
            logger.error('Unable to open changeo file {}'.format(changeo_path))
            sys.exit()
        logger.info('Running TIgGER on {}'.format(subject.identifier))
        cmd = 'run_tigger {} {} {} {} {} {}'.format(
            args.v_germlines,
            changeo_path,
            changeo_path.replace('.changeo.tsv', '.v_genotype.fasta'),
            args.j_max,
            args.min_seqs,
            args.germline_min
        )
        proc = Popen(shlex.split(cmd))
        proc.communicate()
