#!/usr/bin/env python3
import os
import argparse

from .server import get_jass_app
from .config import config

from .models.phenotype import get_available_phenotypes
from .models.inittable import create_inittable_file
from .models.worktable import create_worktable_file
from .models.plots import create_global_plot, create_quadrant_plot


def serve(args):
    app = get_jass_app()
    app.run(host=config["HOST"], port=config["PORT"])


def w_list_phenotypes(args):
    phenotypes = get_available_phenotypes(args.init_table_path)
    print([phenotype.id for phenotype in phenotypes])

def compute_worktable(args):
    init_table_path = args.init_table_path
    selected_phenotypes = args.phenotypes
    worktable_path = args.worktable_path
    remove_nan = not (args.keep_nans)
    significance_treshold = float(args.significance_treshold)
    post_filtering = args.post_filtering
    custom_loadings=args.custom_loadings

    if args.omnibus:
        strategy = 'jass.models.stats:omnibus_stat'
    elif args.sumz:
        strategy = 'jass.models.stats:sumz_stat'
    elif args.fisher_test:
        strategy = "jass.models.stats:fisher_test"
    else:
        strategy = args.strategy

    create_worktable_file(
        selected_phenotypes, init_table_path, worktable_path, remove_nan, strategy, significance_treshold=significance_treshold, post_filtering=post_filtering,
        custom_loadings=custom_loadings
    )

def w_create_worktable(args):
    compute_worktable(args)

def w_create_project_data(args):
    compute_worktable(args)
    worktable_path = args.worktable_path
    manhattan_plot_path = args.manhattan_plot_path
    quadrant_plot_path = args.quadrant_plot_path
    create_global_plot(worktable_path, manhattan_plot_path)
    create_quadrant_plot(worktable_path, quadrant_plot_path, significance_treshold = float(args.significance_treshold))


def w_create_inittable(args):
    input_data_path = args.input_data_path
    init_covariance_path = args.init_covariance_path
    regions_map_path = args.regions_map_path
    description_file_path = args.description_file_path
    init_table_path = args.init_table_path
    create_inittable_file(
        input_data_path,
        init_covariance_path,
        regions_map_path,
        description_file_path,
        init_table_path,
    )

def w_plot_manhattan(args):
    worktable_path = args.worktable_path
    plot_path = args.plot_path
    create_global_plot(worktable_path, plot_path)


def w_plot_quadrant(args):
    worktable_path = args.worktable_path
    plot_path = args.plot_path
    significance_treshold= float(args.significance_treshold)
    create_quadrant_plot(worktable_path, plot_path, significance_treshold=significance_treshold)


def get_parser():
    parser = argparse.ArgumentParser(prog="jass")
    subparsers = parser.add_subparsers(dest="action")
    subparsers.required = True

    parser_serve = subparsers.add_parser("serve", help="run JASS web server")
    parser_serve.set_defaults(func=serve)

    parser_list_phe = subparsers.add_parser(
        "list-phenotypes", help="list phenotypes available in a data file"
    )
    parser_list_phe.add_argument(
        "--init-table-path",
        default=os.path.join(config["DATA_DIR"], "initTable.hdf5"),
        help="path to the initial data file, default is the configured path (JASS_DATA_DIR/initTable.hdf5)",
    )
    parser_list_phe.set_defaults(func=w_list_phenotypes)

    parser_create_pd = subparsers.add_parser(
        "create-project-data",
        help="compute joint statistics and generate plots for a given set of phenotypes",
    )
    parser_create_pd.add_argument(
        "--init-table-path",
        default=os.path.join(config["DATA_DIR"], "initTable.hdf5"),
        help="path to the initial data file, default is the configured path (JASS_DATA_DIR/initTable.hdf5)",
    )
    parser_create_pd.add_argument(
        "--phenotypes", nargs="+", required=True, help="list of selected phenotypes"
    )
    parser_create_pd.add_argument(
        "--worktable-path", required=True, help="path to the worktable file to generate"
    )
    parser_create_pd.add_argument("--keep-nans", action="store_true", default=False)
    parser_create_pd.add_argument(
        "--manhattan-plot-path",
        required=True,
        help="path to the genome-wide manhattan plot to generate",
    )
    parser_create_pd.add_argument(
        "--quadrant-plot-path",
        required=True,
        help="path to the quadrant plot to generate",
    )
    parser_create_pd.add_argument(
        "--significance-treshold",
        default=5*10**-8,
        help="The treshold at which a p-value is considered significant",
    )
    parser_create_pd.add_argument(
        "--post-filtering",
        default=True,
        help="If a filtering to remove outlier will be applied (in this case the result of SNPs considered aberant will not appear in the worktable)",
    )

    parser_create_pd.add_argument(
        "--custom-loadings",
        required=False,
        help="path toward a csv file containing custom loading for sumZ tests",
    )

    strategies = parser_create_pd.add_mutually_exclusive_group()
    strategies.add_argument("--omnibus", action="store_true", default=True)
    strategies.add_argument("--sumz", action="store_true", default=False)
    strategies.add_argument("--fisher_test", action="store_true", default=False)
    strategies.add_argument("--strategy")

    parser_create_pd.set_defaults(func=w_create_project_data)

    parser_create_it = subparsers.add_parser(
        "create-inittable", help="import data into an initial data file"
    )
    parser_create_it.add_argument(
        "--input-data-path",
        required=True,
        help="path to the GWAS data file (ImpG format) to import. the path must be specify between quotes",
    )
    parser_create_it.add_argument(
        "--init-covariance-path",
        required=True,
        help="path to the covariance file to import",
    )
    parser_create_it.add_argument(
        "--regions-map-path",
        required=True,
        help="path to the genome regions map (BED format) to import",
    )
    parser_create_it.add_argument(
        "--description-file-path",
        required=True,
        help="path to the GWAS studies metadata file",
    )
    parser_create_it.add_argument(
        "--init-table-path",
        default=os.path.join(config["DATA_DIR"], "initTable.hdf5"),
        help="path to the initial data file to produce, default is the configured path (JASS_DATA_DIR/initTable.hdf5)",
    )
    parser_create_it.set_defaults(func=w_create_inittable)

    parser_create_wt = subparsers.add_parser(
        "create-worktable",
        help="compute joint statistics for a given set of phenotypes",
    )
    parser_create_wt.add_argument(
        "--init-table-path",
        default=os.path.join(config["DATA_DIR"], "initTable.hdf5"),
        help="path to the initial data table, default is the configured path (JASS_DATA_DIR/initTable.hdf5)",
    )
    parser_create_wt.add_argument(
        "--phenotypes", nargs="+", required=True, help="list of selected phenotypes"
    )
    parser_create_wt.add_argument(
        "--worktable-path", required=True, help="path to the worktable file to generate"
    )
    parser_create_wt.add_argument(
        "--significance-treshold",
        default=5*10**-8,
        help="threshold at which a p-value is considered significant"
        )
    parser_create_wt.add_argument(
        "--post-filtering",
        default=True,
        help="If a filtering to remove outlier will be applied (in this case the result of SNPs considered aberant will not appear in the worktable)"
    )

    parser_create_wt.add_argument(
        "--custom-loadings",
        required=False,
        help="path toward a csv file containing custom loading for sumZ tests",
    )
    parser_create_wt.add_argument("--keep-nans", action="store_true", default=False)
    strategies = parser_create_wt.add_mutually_exclusive_group()
    strategies.add_argument("--omnibus", action="store_true", default=True)
    strategies.add_argument("--sumz", action="store_true", default=False)
    strategies.add_argument("--fisher_test", action="store_true", default=False)
    strategies.add_argument("--strategy")
    parser_create_wt.set_defaults(func=w_create_worktable)

    parser_create_mp = subparsers.add_parser(
        "plot-manhattan",
        help="generate genome-wide manhattan plot for a given set of phenotypes",
    )
    parser_create_mp.add_argument(
        "--worktable-path",
        required=True,
        help="path to the worktable file containing the data",
    )
    parser_create_mp.add_argument(
        "--plot-path", required=True, help="path to the manhattan plot file to generate"
    )
    parser_create_mp.set_defaults(func=w_plot_manhattan)

    parser_create_mp = subparsers.add_parser(
        "plot-quadrant", help="generate a quadrant plot for a given set of phenotypes"
    )
    parser_create_mp.add_argument(
        "--worktable-path",
        required=True,
        help="path to the worktable file containing the data",
    )
    parser_create_mp.add_argument(
        "--plot-path", required=True, help="path to the quadrant plot file to generate"
    )
    parser_create_mp.add_argument(
        "--significance-treshold",
        default=5*10**-8,
        help="threshold at which a p-value is considered significant"
    )
    parser_create_mp.set_defaults(func=w_plot_quadrant)
    return parser

def main():
    parser = get_parser()
    args = parser.parse_args()
    args.func(args)


if __name__ == "__main__":
    main()
