#!/usr/bin/env python
import ConfigParser
import argparse
import ujson
import codecs
import logging
from gelcoverage.runner import GelCoverageRunner


def main():

    parser = argparse.ArgumentParser(description = 'Coverage summary. Provide a panel name and version, a gene list '
                                                   'or none of thee previous to run whole exome coverage analysis')
    parser.add_argument('--bw', metavar='bw', help = 'This coverage bigwig file [required]', required = True)
    parser.add_argument('--output', metavar='output',
                        help='The file to which write the results [required]',
                        required=True)
    parser.add_argument('--config', metavar='config',
                        help='The configuration file [required]',
                        required=True)
    parser.add_argument('--panel', metavar = 'panel',
                        help = 'The PanelApp panel name or identifier /'
                             '(see https://bioinfo.extge.co.uk/crowdsourcing/WebServices/list_panels)',
                        default = None)
    parser.add_argument('--panel-version', metavar = 'panel_version',
                        help='The PanelApp panel version',
                        default = None)
    parser.add_argument('--gene-list', metavar = 'gene_list',
                        default = None,
                        help = 'Comma separated list of genes (HGNC gene symbols) to analyse. Will be masked by a '
                               'panel')
    parser.add_argument('--coding-regions', dest='coding_regions', metavar='coding_regions',
                        help='BED file containing the coding region to analyse and the corresponding annotations. '
                             'If provided skips cellbase connection. The BED file has to be sorted by transcript.',
                        default=None)
    parser.add_argument('--disable-wg-stats', dest='wg_stats_enabled', action='store_false',
                        help='Disable the calculation of whole genome statistics.')
    parser.set_defaults(wg_stats_enabled=True)
    parser.add_argument('--wg-regions', metavar='wg_regions',
                        help='A BED file specifying the regions to be analysed in the whole genome analysis. '
                             'Typically these are the NonN regions in the genome.',
                        default=None)
    parser.add_argument('--disable-coding-region-stats', dest='coding_region_stats_enabled', action='store_false',
                        help='Disable the calculation of coding region statistics.')
    parser.set_defaults(coding_region_stats_enabled=True)
    parser.add_argument('--disable-exon-stats', dest='exon_stats_enabled', action='store_false',
                        help='Disable the calculation of exon statistics. Use this flag when running a coverage '
                             'analysis on whole exome to minimise the space taken by the output JSON.')
    parser.set_defaults(exon_stats_enabled=True)
    parser.add_argument('--coverage-threshold', metavar='coverage_threshold',
                        help='The coverage threshold used to compute continuous gaps with low coverage '
                             '(0 = disabled) [default:15]',
                        default=15)

    args = parser.parse_args()

    # Reads configuration file
    config_parser = ConfigParser.ConfigParser()
    config_parser.readfp(open(args.config))

    # Creates a data structure with all config parameters
    config = {
        # Sets parameters from CLI
        "bw": args.bw,
        "panel": args.panel,
        "panel_version": args.panel_version,
        "gene_list": args.gene_list,
        "coverage_threshold": args.coverage_threshold,
        "coding_regions": args.coding_regions,
        "wg_stats_enabled": args.wg_stats_enabled,
        "wg_regions": args.wg_regions,
        "exon_stats_enabled": args.exon_stats_enabled,
        "coding_region_stats_enabled": args.coding_region_stats_enabled,
        # Sets parameters from config file
        'configuration_file': args.config,
        "panelapp_host": config_parser.get('panelapp', 'host'),
        "panelapp_gene_confidence": config_parser.get('panelapp', 'gene_confidence'),
        "panelapp_retries": int(config_parser.get('panelapp', 'retries')),
        "panelapp_assembly": config_parser.get('cellbase', 'assembly'),
        "transcript_filtering_flags": config_parser.get('transcript_filtering', 'flags'),
        "transcript_filtering_biotypes": config_parser.get('transcript_filtering', 'biotypes'),
        "exon_padding": int(config_parser.get("exon", "exon_padding")),
        "log_level": int(config_parser.get("logging", "level")),
        'cellbase_host': config_parser.get('cellbase', 'host'),
        'cellbase_species': config_parser.get('cellbase', 'species'),
        'cellbase_version': config_parser.get('cellbase', 'version'),
        'cellbase_assembly': config_parser.get('cellbase', 'assembly'),
        'cellbase_retries': int(config_parser.get('cellbase', 'retries'))
    }
    # Calls the GEL coverage engine
    gel_coverage_engine = GelCoverageRunner(config)
    (results, bed) = gel_coverage_engine.run()
    # Prints output to stdout
    # TODO: we may want to write it to a file. Check that
    with codecs.open(args.output, 'w', 'utf8') as output_file:
        output_file.write(
            ujson.dumps(
                results,
                ensure_ascii=False
            )
        )
    # Saves the analysed region as a BED file
    if bed is not None and not args.coding_regions:
        bed.saveas(args.output + ".bed")

if __name__ == '__main__':
    main()
