#!/usr/bin/env python3.6

import argparse
import datetime
import subprocess
import sys
import os
from pathlib import Path

import yaml
import tqdm

import knock_knock

citation = '''
Hera Canaj, Jeffrey A. Hussmann, Han Li, Kyle A. Beckman, Leeanne Goodrich,
Nathan H. Cho, Yucheng J. Li, Daniel A Santos, Aaron McGeever, Edna M Stewart,
Veronica Pessino, Mohammad A Mandegar, Cindy Huang, Li Gan, Barbara Panning,
Bo Huang, Jonathan S. Weissman and Manuel D. Leonetti.  "Deep profiling reveals
the complexity of integration outcomes in CRISPR knock-in experiments."
https://www.biorxiv.org/content/10.1101/841098v1 (2019).
'''

def check_blastn(require_precise_version=False):
    no_blastn = False

    try:
        output = subprocess.check_output(['blastn', '-version'])
        if require_precise_version and b'2.7.1' not in output:
            print('blastn 2.7.1 is required and couldn\'t be found')
            sys.exit(0)
    except:
        print('blastn is required and couldn\'t be found')
        sys.exit(0)

def check_parallel():
    no_parallel = False

    try:
        output = subprocess.check_output(['parallel', '--version'])
        if not output.startswith(b'GNU parallel'):
            no_parallel = True
    except:
        no_parallel = True

    if no_parallel:
        print('GNU parallel is required and couldn\'t be found')
        sys.exit(0)

def parallel(args):
    from knock_knock import experiment

    check_parallel()

    if args.group:
        args.conditions['batch'] = args.group

    exps = experiment.get_all_experiments(args.project_directory, args.conditions)

    if len(exps) == 0:
        print('No experiments satify conditions:')
        print(args.conditions)
        sys.exit(0)

    if args.show_progress_bars:
        possibly_progress = ['--bar']
    else:
        possibly_progress = []

    parallel_command = [
        'parallel',
        '--will-cite',
        '-n', '4', 
    ] + possibly_progress + [
        '--max-procs', str(args.max_procs),
        'knock-knock',
        'process',
        str(args.project_directory),
        ':::',
    ]

    arg_tuples = [(batch, sample_name, '--stages', args.stages) for batch, sample_name in exps]
    for t in sorted(arg_tuples):
        parallel_command.extend(t)

    env = os.environ
    env['OPENBLAS_NUM_THREADS'] = '1'

    completed_process = subprocess.run(parallel_command, env=env)
    if completed_process.returncode != 0:
        print('error in parallel')
        sys.exit(1)

def process(args):
    from knock_knock import experiment

    check_blastn()

    sample_sheet = experiment.load_sample_sheet(args.project_directory, args.group)

    if sample_sheet is None:
        print(f'Error: {args.group} not found in {args.project_directory}')
        sys.exit(1)
    elif args.sample not in sample_sheet:
        print(f'Error: {args.sample} not found in {args.group} sample sheet')
        sys.exit(1)
    else:
        description = sample_sheet[args.sample]

    exp_class = experiment.get_exp_class(description.get('platform'))
    exp = exp_class(args.project_directory, args.group, args.sample, description=description, progress=args.progress)

    stages = args.stages.split(',')

    def timestamp():
        return f'{datetime.datetime.now():%Y-%m-%d %H:%M:%S}'

    for stage in stages:
        print(f'{timestamp()} Started {exp.batch}: {exp.sample_name} {stage}')
        exp.process(stage)
        print(f'{timestamp()} Finished {exp.batch}: {exp.sample_name} {stage}')

def make_tables(args):
    from knock_knock import experiment, table

    results_dir = args.project_directory / 'results'

    if args.group:
        groups = [args.group]
    else:
        groups = experiment.get_all_batches(args.project_directory)

        results_dir = args.project_directory / 'results'
        csv_fn = (results_dir / 'all_groups').with_suffix('.csv')
        df = table.load_counts(args.project_directory, exclude_empty=False).T
        df.to_csv(csv_fn)

    for group in groups:
        print(group)

        conditions = {'batch': group}

        table.make_self_contained_zip(args.project_directory, conditions, group, sort_samples=not args.unsorted)

def build_targets(args):
    from knock_knock import build_targets
    build_targets.build_target_infos_from_csv(args.project_directory,
                                              offtargets=args.offtargets,
                                              defer_HA_identification=args.defer_HA_identification,
                                             )

def build_manual_target(args):
    from knock_knock import build_targets
    build_targets.build_manual_target(args.project_directory, args.target_name)

def design_primers(args):
    from knock_knock import build_targets
    build_targets.design_amplicon_primers_from_csv(args.project_directory, args.genome)

def build_indices(args):
    from knock_knock import build_targets
    build_targets.download_genome_and_build_indices(args.project_directory,
                                                    args.genome_name,
                                                    args.num_threads
                                                   )

def install_example_data(args):
    import os
    import shutil

    package_dir = Path(os.path.realpath(knock_knock.__file__)).parent
    subdirs_to_copy = ['data', 'targets']
    for subdir in subdirs_to_copy:
        src = package_dir / 'example_data' / subdir
        dest = args.project_directory / subdir

        if dest.exists():
            print(f'Can\'t install to {args.project_directory}, {dest} already exists')
            sys.exit(0)

        shutil.copytree(str(src), str(dest))

    print(f'Example data installed in {args.project_directory}')

def print_citation(args):
    print(citation)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(prog='knock-knock')

    parser.add_argument('--version', action='version', version=knock_knock.__version__)

    subparsers = parser.add_subparsers(dest='subcommand', title='subcommands')
    subparsers.required = True

    def add_project_directory_arg(parser):
        parser.add_argument('project_directory', type=Path, help='the base directory to store input data, reference annotations, and analysis output for a project')

    parser_process = subparsers.add_parser('process', help='process a single sample')
    add_project_directory_arg(parser_process)
    parser_process.add_argument('group', help='group name')
    parser_process.add_argument('sample', help='sample name')
    parser_process.add_argument('--progress', const=tqdm.tqdm, action='store_const', help='show progress bars')
    parser_process.add_argument('--stages', default='preprocess,align,categorize,visualize')
    parser_process.set_defaults(func=process)

    parser_parallel = subparsers.add_parser('parallel', help='process multiple samples in parallel')
    add_project_directory_arg(parser_parallel)
    parser_parallel.add_argument('max_procs', type=int, help='maximum number of samples to process at once')
    parser_parallel.add_argument('--group', help='if specified, the single group name to process; if not specified, all groups will be processed')
    parser_parallel.add_argument('--conditions', type=yaml.safe_load, default={}, help='if specified, conditions that samples must satisfy to be processed, given as yaml; if not specified, all samples will be processed')
    parser_parallel.add_argument('--stages', default='preprocess,align,categorize,visualize')
    parser_parallel.add_argument('--show_progress_bars', action='store_true')
    parser_parallel.set_defaults(func=parallel)

    parser_table = subparsers.add_parser('table', help='generate tables of outcome frequencies')
    add_project_directory_arg(parser_table)
    parser_table.add_argument('--group', help='if specified, the single group name to generate tables for; if not specified, all groups will be generated')
    parser_table.add_argument('--unsorted', action='store_true', help='don\'t sort samples')
    parser_table.set_defaults(func=make_tables)

    parser_targets = subparsers.add_parser('build-targets', help='build annotations of target locii')
    add_project_directory_arg(parser_targets)
    parser_targets.add_argument('--offtargets', action='store_true', help='don\'t enforce PAMs')
    parser_targets.add_argument('--defer_HA_identification', action='store_true', help='don\'t try to identiy homology arms')
    parser_targets.set_defaults(func=build_targets)

    parser_manual_target = subparsers.add_parser('build-manual-target', help='build a single target from a hand-annotated genbank file')
    add_project_directory_arg(parser_manual_target)
    parser_manual_target.add_argument('target_name', help='sample name')
    parser_manual_target.set_defaults(func=build_manual_target)

    parser_primers = subparsers.add_parser('design-primers', help='design amplicon primers for sgRNAs')
    add_project_directory_arg(parser_primers)
    parser_primers.add_argument('--genome', default='hg19')
    parser_primers.set_defaults(func=design_primers)

    parser_indices = subparsers.add_parser('build-indices', help='download a reference genome and build alignment indices')
    add_project_directory_arg(parser_indices)
    parser_indices.add_argument('genome_name', help='name of genome to download')
    parser_indices.add_argument('--num-threads', type=int, default=8, help='number of threads to use for index building')
    parser_indices.set_defaults(func=build_indices)

    parser_install_data = subparsers.add_parser('install-example-data', help='install example data into user-specified project directory')
    add_project_directory_arg(parser_install_data)
    parser_install_data.set_defaults(func=install_example_data)

    parser_citation = subparsers.add_parser('whos-there', help='print citation information')
    parser_citation.set_defaults(func=print_citation)

    args = parser.parse_args()
    args.func(args)
