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

Command Line Interface for ped_parser

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

from __future__ import print_function

import sys
import os
import click

from datetime import datetime

from codecs import open

from ped_parser import FamilyParser, init_log, logger, __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('ped_parser version: ' + __version__)
    ctx.exit()


###         This is the main script         ###

@click.command()
@click.argument('family_file', 
                    nargs=1, 
                    type=click.File('r'),
                    metavar='<family_file> or -'
)
@click.option('-t', '--family_type',
                    type=click.Choice(['ped', 'alt', 'cmms', 'mip']),
                    default='ped',
                    help='If the analysis use one of the known setups, please specify which one. Default is ped'
)
@click.option('-o', '--outfile', 
                    type=click.File('a'),
                    help='Specify the path to a file where results should be stored.'
)
@click.option('--cmms_check', 
                    is_flag=True,
                    help='If the id is in cmms format.'
)
@click.option('--to_json', 
                    is_flag=True,
                    help='Print the ped file in json format.'
)
@click.option('--to_madeline', 
                    is_flag=True,
                    help='Print the ped file in madeline format.'
)
@click.option('--to_ped', 
                    is_flag=True,
                    help='Print the ped file in ped format with headers.'
)
@click.option('--to_dict', 
                    is_flag=True,
                    help='Print the ped file in ped format with headers.'
)
@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
)
@click.option('-l', '--logfile',
                    type=click.Path(exists=False),
                    help="Path to log file. If none logging is "\
                          "printed to stderr."
)
@click.option('--loglevel',
                    type=click.Choice(['DEBUG', 'INFO', 'WARNING', 'ERROR',
                                        'CRITICAL']),
                    help="Set the level of log output."
)
def cli(family_file, family_type, outfile, to_json, to_madeline, 
                cmms_check, to_ped, to_dict, verbose, logfile, loglevel):
    """Tool for parsing ped files.\n
        Default is to prints the family file to in ped format to output. 
        For more information, please see github.com/moonso/ped_parser.
    """
    from pprint import pprint as pp
    
    if not loglevel:
        if verbose:
            loglevel = 'INFO'
        else:
            loglevel = 'WARNING'

    # Setup the logging environment
    init_log(logger, logfile, loglevel)

    my_parser = FamilyParser(family_info=family_file, family_type=family_type, 
                                    cmms_check=cmms_check)

    start = datetime.now()
    logger.info('Families found in file: {0}'.format(
                    ','.join(list(my_parser.families.keys()))
                    ) 
                )

    if to_json:
        if outfile:
            outfile.write(my_parser.to_json())
        else:
            print(my_parser.to_json())

    elif to_madeline:
        for line in my_parser.to_madeline():
            if outfile:
                outfile.write(line + '\n')
            else:
                print(line)

    elif to_ped:
        for line in my_parser.to_ped():
            if outfile:
                outfile.write(line + '\n')
            else:
                print(line)

    elif to_dict:
        pp(my_parser.to_dict())

    else:
        # If no specific output is choosen, write a summary about the families to screen
        for family in my_parser.families:
            logger.info('Fam: {0}'.format(family))
            if family_type in ['cmms', 'mip']:
                logger.info('Expected Inheritance Models: {0}'.format(
                            my_parser.families[family].models_of_inheritance
                            ) 
                        )
            logger.info('Individuals: ')
            for individual in my_parser.families[family].individuals:
                logger.info(my_parser.families[family].individuals[individual])
            logger.info('Affected individuals: {0} \n'.format(
                    ','.join(my_parser.families[family].affected_individuals)
                        )
                    )
    

if __name__ == '__main__':
    cli()
