#!/usr/bin/env python
# encoding: utf-8
"""
vcf_parser

Command Line Interface for vcf_parser

Created by Måns Magnusson on 2014-12-12.
Copyright (c) 2014 __MoonsoInc__. All rights reserved.
"""

from __future__ import print_function
from __future__ import unicode_literals

import sys
import os
import click

from pprint import pprint as pp

from codecs import getwriter

import pkg_resources
import vcf_parser
from vcf_parser import parser

if sys.version_info < (3,0):
    sys.stdout = getwriter('UTF-8')(sys.stdout)

version = pkg_resources.require("vcf_parser")[0].version


def print_version(ctx, param, value):
    """Callback function for printing version and exiting
    Args:
        ctx (object) : Current context
        param (object) : Click parameter(s)
        value (boolean) : Click parameter was supplied or not
    Returns:
        None:
    """
    if not value or ctx.resilient_parsing:
        return
    click.echo('vcf_parser version: ' + version)
    ctx.exit()


###         This is the main script         ###

@click.command()
@click.argument('variant_file', 
                    nargs=1, 
                    type=click.Path(),
                    metavar='<vcf_file> or -'
)
@click.option('-v', '--vep', 
                    is_flag=True,
                    help='If variants are annotated with the Variant Effect Predictor.'
)
@click.option('-s', '--split', 
                    is_flag=True,
                    help='Split the variants with multiallelic calls.'
)
@click.option('-o', '--outfile', 
                    type=click.Path(exists=False),
                    help='Specify the path to a file where results should be stored.'
)
@click.option('-v', '--verbose', 
                is_flag=True,
                help='Increase output verbosity.'
)
@click.option('--version',
                is_flag=True,
                callback=print_version,
                expose_value=False,
                is_eager=True
)
def vcf_parser(variant_file, vep, split, outfile, verbose):
    """Tool for parsing vcf files.\n
        Prints the vcf file to output. If --split/-s is used all multiallelic calls will be splitted and printed as single variant calls.
        For more information, please see github.com/moonso/vcf_parser.
    """
    from datetime import datetime
    if variant_file == '-':
        my_parser = parser.VCFParser(fsock=sys.stdin, split_variants=split)
    else:
        my_parser = parser.VCFParser(infile = variant_file, split_variants=split)
    start = datetime.now()
    nr_of_variants = 0
    if outfile:
        with open(outfile, 'w', encoding='utf-8') as f:
            for line in my_parser.metadata.print_header():
                f.write(line+'\n')
            for variant in my_parser:
                f.write('\t'.join([variant[head] for head in my_parser.header])+'\n')
                nr_of_variants += 1
    else:
        for line in my_parser.metadata.print_header():
            print(line)
        for variant in my_parser:
            print('\t'.join([variant[head] for head in my_parser.header]))        
            nr_of_variants += 1
    if verbose:
        print('Number of variants: %s' % nr_of_variants)
        print('Time to parse file: %s' % str(datetime.now() - start))
    

if __name__ == '__main__':
    vcf_parser()
