"""
astk.cli.suppa
~~~~~~~~~~~~~~~~~
This module provide cli api for suppa2 function
"""

from .config import *
from ..suppa import *
from astk.constant import AS_TYPE


@cli_fun.command(name="generateEvents", help="generate the events from the GTF file; short alias:ge")
@click.option('-gtf', '--gtf', type=click.Path(exists=True), help="a GTF format file")
@click.option('-et', '--eventType', "event_types", type=click.Choice(['ALL'] + AS_TYPE), 
                default="ALL", help="AS event Type")
@click.option('-o', '--output', required=True, 
                help="name of the output file without any extension")
@click.option('--id-type', "idtype", default="SUPPA2", type=click.Choice(["SUPPA2"]), 
                show_default=True, help="output event ID type") 
@click.option('-ep','--event-pos', type=click.Choice(['body', 'FT', 'LT']), 
                help="AS event exon that overlapping the transcript first or last \
                        terminal exon startCodon and stopCodon will save separately")
def generateEvents(*args, **kwargs):
    generate_events(*args, **kwargs)


@cli_fun.command(name="generatePsi", help="calculates AS events PSI values; alias: ge, psiPerEvent")
@click.option('-o', '--output', type=click.Path(), required=True, help="output file path")
@click.option('-ioe', '--ioe', type=click.Path(exists=True), help="ioe file path")
@click.option('-qf', '--quantifyFile', "tpm_files", cls=MultiOption, type=click.Path(exists=True),
                help="transcript quantification files")
@click.option('--tpmThreshold', "tpm_th", type=float, default=0, show_default=True,
                help="minimum transcript TPM value that using for calculates PSI")                
@click.option('--tpm-col', "tpm_col", type=int, default=4, show_default=True, 
                help="TPM columns index, 1-based")
@click.option('--txCol', "tx_col", type=int, default=0, show_default=True,
                help="transcript ID columns index, 1-based")
def generatePsi(*args, **kwargs):
    from pathlib import Path
    
    output = kwargs.pop("output")
    psi_df, tpm_df = calculate_psi(*args, **kwargs)
    psi_df.to_csv(output, sep="\t")
    tpm_df.to_csv(Path(output).with_suffix(".tpm"), sep="\t", index_label=False)


@cli_fun.command(name="diffSplice", help="differential splicing analysis; short alias: ds")
@click.option('-psi', '--psiFile', "psi_files", cls=MultiOption, required=True, 
                type=click.Path(exists=True),  help="AS event PSI files")
@click.option('-exp', '--expressFile', "exp_files", cls=MultiOption, required=True, 
                type=click.Path(exists=True), help="transcript TPM quantification files")
@click.option('-ref', '--reference', type=click.Path(exists=True),
                help="ioe reference file")
@click.option('-o', '--output', help="output directory")
@click.option('-m', '--method', type=click.Choice(['empirical', 'classical']), show_default=True,
                default="empirical", help="The method to calculate the significance")
@click.option('-th', '--tpm-threshold', type=float, default=0, show_default=True,
                help="Minimum expression to be included in the analysis.")
@click.option('-gc', '--gene-correction', is_flag=True, default=False, show_default=True,
                help="Correction of the p-values by gene.")
@click.option('-adpsi', '--adpsi-threshold', type=float, default=0, show_default=True,
                help="cut-off for the absolute delta PSI value to test for significance. \
                Events with less than this delta PSI will not be tested. (Note: it is only \
                implemented in the empirical method.)")
def diffSplice(*args, **kwargs):
    diff_splice(*args, **kwargs)


@cli_fun.command(help="differential splicing analysis workflow")
@click.option('-od', '--outdir', required=True, help="output directory")
@click.option('-md', '--metadata', type=click.Path(exists=True),
             help="contrast group metadata, generated by meta")
@click.option('-gtf', '--gtf', type=click.Path(exists=True), help="gene annotation gtf file")
@click.option('-et', '--event-type', type=click.Choice(['ALL']+AS_TYPE), cls=MultiOption,
                default="ALL", show_default=True, help="AS event type")
@click.option('-m', '--method', type=click.Choice(['empirical', 'classical']), default="empirical",
                show_default=True, help="The method to calculate the significance")
@click.option('-p', '--pval', type=click.FloatRange(min=0, max=1), 
                default=0.05, show_default=True, help="pval threshold  value")
@click.option('-adpsi', '--abs-dpsi', type=click.FloatRange(min=0, max=1), 
                default=0.1, show_default=True, help="absulte dpsi threshold value")
@click.option('--id-type', default="SUPPA2", type=click.Choice(["SUPPA2"]), 
                show_default=True, help="output event ID type")          
@click.option('--exon-len', type=int, default=100,
             help="Defines the number of nucleotides to display in the output GTF. (Default: 100 nt)")             
@click.option('-pg', '--pool-genes', default=False, is_flag=True, 
             help="pool together overlapping genes")
@click.option('--tpm-col', "tpm_col", type=int, default=4, show_default=True, 
                help="TPM columns index, 1-based")
@click.option('--tpm-threshold', type=float, default=0, 
                help="Minimum TPM value to be included in the analysis. default=0")
@click.option('-ep','--event-pos', type=click.Choice(['body', 'FT', 'LT']), 
                help="AS event exon that overlapping the transcript first or last \
                        terminal exon startCodon and stopCodon will save separately")                
def dsflow(*args, **kwargs):
    if "ALL" in kwargs.get("event_type"):
        etypes = AS_TYPE
    else:
        etypes = kwargs.get("event_type")
    ds_flow(kwargs.get("metadata"),
        kwargs.get("gtf"),
        etypes,
        kwargs.get("outdir"),
        kwargs.get("method"),
        kwargs.get("id_type"),
        kwargs.get("pval"),
        kwargs.get("abs_dpsi"),
        kwargs.get("tpm_threshold"),
        kwargs.get("event_pos"),
        kwargs.get("tpm_col")
    )
