# /user/bin/env python3
# -*- coding: utf-8 -*-
"""Main class."""

import argparse

import logging

from lc18report_dev.report_maker import ReportMaker


def _set_logging(log_dir: str, debug_mode: int) -> None:
    # Set logging.
    fileName = 'report.log'
    logFormatter = logging.Formatter(
        '%(asctime)s [%(threadName)-12.12s] [%(levelname)-7.7s]  %(message)s')
    fileHandler = logging.FileHandler('{0}/{1}'.format(log_dir, fileName))
    fileHandler.setFormatter(logFormatter)
    consoleHandler = logging.StreamHandler()
    consoleHandler.setFormatter(logFormatter)
    logging.basicConfig(
        level=debug_mode,
        handlers=[fileHandler, consoleHandler]
    )


def run_server_mode(args: dict) -> int:
    print("<run_server_mode>")
    try:
        input_xlsx = args['input_xlsx']
        record_xlsx = args['record_xlsx']
        output_dir = args['output_dir']
        template_version = args['template_version']
        yuedong_template_version = args['yuedong_template_version']
        sample_info_file = args['sample_info_file']
        lab_info_file = args['lab_info_file']
        kdb_file = args['kdb_file']
        base_info_file = args['base_info_file']
        log_dir = args['log_dir']
        debug_mode = logging.DEBUG if args['debug_mode'] else logging.INFO
        add_suffix = args.get('add_suffix', False)
        db_file = args['db_file']
        force_mode = args['force_mode']
        selected_samples = args['selected_samples']

        _set_logging(log_dir, debug_mode)
        report_maker = ReportMaker(force_mode=force_mode)
        report_maker.set_db(db_file)
        report_maker.set_kdb_file_current(kdb_file)
        report_maker.set_template_version(template_version, yuedong_template_version)
        report_maker.set_base_file(base_info_file, record_xlsx)
        report_maker.set_info(sample_info_file=sample_info_file, lab_info_file=lab_info_file)
        report_maker.set_selected_samples(selected_samples)

        return_code = report_maker.make(input_xlsx, output_dir, timed=add_suffix)
    except Exception as e:
        raise e
    else:
        return return_code


def run_app_to_data(args: dict) -> int:
    print("<run_app_to_data>")
    input_xlsx = args['input_xlsx']
    output_dir = args['output_dir']
    template_version = args['template_version']
    yuedong_template_version = args['yuedong_template_version']
    log_dir = args['log_dir']
    debug_mode = logging.DEBUG if args['debug_mode'] else logging.INFO
    info_file = args['info_file']
    add_suffix = args['add_suffix']
    force_mode = args['force_mode']
    en_mode = args['en_mode']

    _set_logging(log_dir, debug_mode)
    report_maker = ReportMaker(force_mode=force_mode, en_mode=en_mode)
    report_maker.set_template_version(template_version, yuedong_template_version)
    report_maker.set_info(merged_info_file=info_file)

    return_code = report_maker.make(
        input_xlsx, output_dir, out_type='data', timed=add_suffix)
    return return_code


def run_app_report(args: dict) -> int:
    print("<run_app_report>")
    data_path = args['data_path']
    output_path = args['output_path']
    log_dir = args['log_dir']
    en_mode = args['en_mode']
    debug_mode = logging.DEBUG if args['debug_mode'] else logging.INFO

    _set_logging(log_dir, debug_mode)
    report_maker = ReportMaker(en_mode=en_mode)

    return_code = report_maker.data2report(
        data_path, output_path)
    return return_code


def main():
    _default_template_version = '2.4'
    _default_yuedong_template_version = "2.6.2"

    parser = argparse.ArgumentParser(description='18 Gene report generator.')
    subparsers = parser.add_subparsers()
    server_mode_parser = subparsers.add_parser('server_mode')
    app_data_parser = subparsers.add_parser('app_data')
    app_report_parser = subparsers.add_parser('app_report')

    server_mode_parser.set_defaults(function=run_server_mode)
    server_mode_parser.add_argument(
        '-i', '--input', dest='input_xlsx', type=str, required=True,
        help='Excel file output of 18 gene analysis pipeline.'
    )
    server_mode_parser.add_argument(
        '-I', '--selected_samples', dest='selected_samples', type=str,
        default='ALL', required=False,
        help='指定本批次中要分析的样本，默认是分析全部样本'
    )
    server_mode_parser.add_argument(
        '-o', '--output_dir', dest='output_dir', type=str, required=True,
        help='Output dir for report word documents.'
    )
    server_mode_parser.add_argument(
        '--template', dest='template_version', type=str,
        default=_default_template_version,
        help='Report template version.'
    )
    server_mode_parser.add_argument(
        '--yuedong_template', dest='yuedong_template_version', type=str,
        default=_default_yuedong_template_version,
        help='Report 阅动/yuedong template version.'
    )
    server_mode_parser.add_argument(
        '-s', '--sample_info_file', dest='sample_info_file', type=str,
        required=True,
        help='Sample info file.'
    )
    server_mode_parser.add_argument(
        '-l', '--lab_info_file', dest='lab_info_file', type=str,
        required=True,
        help='Lab info file.'
    )
    server_mode_parser.add_argument(
        '-r', '--record_xlsx', dest='record_xlsx', type=str,
        required=True,
        help='Record xlsx.'
    )
    server_mode_parser.add_argument(
        '-b', '--base_info_file', dest='base_info_file', type=str,
        required=True,
        help='Base info file.'
    )
    server_mode_parser.add_argument(
        '-k', '--kdb', dest='kdb_file', type=str, required=True,
        help='Report knowledge database file.'
    )
    server_mode_parser.add_argument(
        '-d', '--db_file', dest='db_file', type=str, required=True,
        help='YueDong database file.'
    )
    server_mode_parser.add_argument(
        '--log_dir', dest='log_dir', type=str, default='.',
        help='Custom report log dir location.'
    )
    server_mode_parser.add_argument(
        '--debug', dest='debug_mode', action='store_true',
        help='Debug mode.'
    )
    server_mode_parser.add_argument(
        '--suffix', dest='add_suffix', action='store_true',
        help='Add time-based suffix to output filename.'
    )
    server_mode_parser.add_argument(
        '-f', '--force_mode', dest='force_mode', action='store_true',
        help='Force report output for variant with missing kdb record as type'
        ' 3 variants.'
    )
    server_mode_parser.add_argument(
        '-e', '--en_mode', dest='en_mode', action='store_true',
        help='Generate english report with english version of kdb and template.'
    )

    app_data_parser.set_defaults(function=run_app_to_data)
    app_data_parser.add_argument(
        '-i', '--input', dest='input_xlsx', type=str, required=True,
        help='Excel file output of 18 gene analysis pipeline.'
    )
    app_data_parser.add_argument(
        '-s', '--sample_info_file', dest='info_file', type=str, required=True,
        help='Sample info file.'
    )
    app_data_parser.add_argument(
        '-r', '--record_xlsx', dest='record_xlsx', type=str, required=True,
        help='Record xlsx.'
    )
    app_data_parser.add_argument(
        '-b', '--base_info_file', dest='base_info_file', type=str, required=True,
        help='Base info file.'
    )
    app_data_parser.add_argument(
        '-o', '--output_dir', dest='output_dir', type=str, required=True,
        help='Output dir for sample report json files.'
    )
    app_data_parser.add_argument(
        '--template', dest='template_version', type=str,
        default=_default_template_version,
        help='Report template version.'
    )
    app_data_parser.add_argument(
        '--yuedong_template', dest='yuedong_template_version', type=str,
        default=_default_yuedong_template_version,
        help='Report 阅动/yuedong template version.'
    )
    app_data_parser.add_argument(
        '--log_dir', dest='log_dir', type=str, default='.',
        help='Custom report log dir location.'
    )
    app_data_parser.add_argument(
        '--debug', dest='debug_mode', action='store_true',
        help='Debug mode.'
    )
    app_data_parser.add_argument(
        '--suffix', dest='add_suffix', action='store_true',
        help='Add time-based suffix to output filename.'
    )
    app_data_parser.add_argument(
        '-f', '--force_mode', dest='force_mode', action='store_true',
        help='Force report output for variant with missing kdb record as type'
        ' 3 variants.'
    )
    app_data_parser.add_argument(
        '-e', '--en_mode', dest='en_mode', action='store_true',
        help='Generate english report with english version of kdb and template.'
    )

    app_report_parser.set_defaults(function=run_app_report)
    app_report_parser.add_argument(
        '-d', '--data', dest='data_path', type=str, required=True,
        help='The path of data file containing report content for sample.'
    )
    app_report_parser.add_argument(
        '-o', '--output_path', dest='output_path', type=str, required=True,
        help='Output file path for report word documents.'
    )
    app_report_parser.add_argument(
        '--log_dir', dest='log_dir', type=str, default='.',
        help='Custom report log dir location.'
    )
    app_report_parser.add_argument(
        '--debug', dest='debug_mode', action='store_true',
        help='Debug mode.'
    )
    app_report_parser.add_argument(
        '-e', '--en_mode', dest='en_mode', action='store_true',
        help='Generate english report with english version of kdb and template.'
    )

    try:
        args = parser.parse_args()
        return_code = args.function(vars(args))
        exit(return_code)
    except AttributeError as e:
        parser.print_help()
        exit(2)

if __name__ == '__main__':
    main()
