#!/usr/bin/env python
# -*- coding: UTF-8 -*-

"""
python %prog study.file population.file gene-association.file

This program returns P-values for functional enrichment in a cluster of
study genes using Fisher's exact test, and corrected for multiple testing
(including Bonferroni, Holm, Sidak, and false discovery rate)
"""

from __future__ import print_function
from __future__ import absolute_import


__copyright__ = "Copyright (C) 2010-present, H Tang et al., All rights reserved."
__author__ = "various"

import sys
import datetime


class GoeaPrintFunctions:
    """Functions for displaying GOEA results"""

    @staticmethod
    def print_date(min_ratio=None, pval=0.05):
        """Print GOATOOLS version and the date the GOEA was run."""
        import goatools

        # Header contains provenance and parameters
        date = datetime.date.today()
        print("# Generated by GOATOOLS v{0} ({1})".format(goatools.__version__, date))
        print("# min_ratio={0} pval={1}".format(min_ratio, pval))

    def print_results(self, results, min_ratio=None, indent=False, pval=0.05, prt=sys.stdout):
        """Print GOEA results with some additional statistics calculated."""
        results_adj = self.get_adj_records(results, min_ratio, pval)
        self.print_results_adj(results_adj, indent, prt)

    def print_results_adj(self, results, indent=False, prt=sys.stdout):
        """Print GOEA results."""
        # Print column headers if there are results to be printed
        if results:
            prt.write("{R}\n".format(R="\t".join(self.get_prtflds_default(results))))
        # Print the GOEA results
        for rec in results:
            prt.write("{R}\n".format(R=rec.__str__(indent=indent)))

    @staticmethod
    def get_prtflds_default(results):
        """Get default fields names. Used in printing GOEA results.

           Researchers can control which fields they want to print in the GOEA results
           or they can use the default fields.
        """
        if results:
            return results[0].get_prtflds_default()
        return []

    @staticmethod
    def get_adj_records(results, min_ratio=None, pval=0.05):
        """Return GOEA results with some additional statistics calculated."""
        records = []
        if pval is not None and 0.0 <= pval < 1.0:
            results = [r for r in results if r.p_uncorrected < pval]
        for rec in results:
            # calculate some additional statistics
            # (over_under, is_ratio_different)
            rec.update_remaining_fldsdefprt(min_ratio=min_ratio)

            if rec.is_ratio_different:
                records.append(rec)
        return records


# Copyright (C) 2010-present, H Tang et al., All rights reserved.
