# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/chiSq.ipynb (unless otherwise specified).

__all__ = ['ChiSqLandingView', 'ChiSqModel', 'ChiSqIndModel', 'ChiSqConModel', 'ChiSqEstimatesView']

# Cell
import ipywidgets as ipyw
import traitlets
from traitlets import observe, Unicode
import numpy as np
from fastcore.test import test_eq
from IPython.display import display, Javascript

# Cell
from .custom_widgets.ratio import RatioLandingView, RatioEstimatesModel, RatioEstimatesView
from .view.widget_collections import VBox, Box, HBox
from .view.widgets import Textarea, Button
from .model.model import RFunction
from .model.model_collections import Collection
from .rpy import Float, IntArray
from .globals import LinkAllMixin, AddStringsMixin

# Cell
class ChiSqLandingView(RatioLandingView):
    pass

# Cell
class ChiSqModel(RatioEstimatesModel, AddStringsMixin):

    pVal = Float(.05)
    mata = IntArray()
    matb = IntArray()
    rcomp = Float(.3)
    effectStrA = Unicode()
    effectStrB = Unicode()
    w = Float()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def _color_mats(self):
        self.mata = []
        self.matb = []
        self.effectStrA = ''
        self.effectStrB = ''
        colors = np.array(self.colors, dtype=np.unicode_)
        if not np.all(colors == 'none'):
            if not np.any(colors == 'green') and not np.any(colors == 'red'):
                raise Exception('Both self.colors must be selected to perform chi squared with contrast.')
            else:
                first_red = True
                first_green = True
                for i, row in enumerate(self.ns_cells):
                    if np.any(colors[i] == 'red'):
                        if first_red:
                            red_pattern = colors[i] == 'red'
                            self.mata = row[red_pattern]
                            first_red = False
                        else:
                            assert np.array_equal(colors[i] == 'red', red_pattern), 'Selected self.colors should be the same for every selected row.'
                            self.mata = np.vstack((self.mata, row[red_pattern]))
                        colNames = self.colLevelNames[red_pattern]
                        rowName = self.rowLevelNames[i]
                        row_strs = self.add_strings(rowName, colNames)
                        row_str = np.array2string(row_strs, separator=',', prefix='', suffix='', formatter={'object':lambda x: x})
                        self.effectStrA += row_str
                    if np.any(colors[i] == 'green'):
                        if first_green:
                            green_pattern = colors[i] == 'green'
                            self.matb = row[green_pattern]
                            first_green = False
                        else:
                            assert np.array_equal(colors[i] == 'green', green_pattern), 'Selected self.colors should be the same for every selected row.'
                            self.matb = np.vstack((self.matb, row[green_pattern]))
                        colNames = self.colLevelNames[green_pattern]
                        rowName = self.rowLevelNames[i]
                        row_strs = self.add_strings(rowName, colNames)
                        row_str = np.array2string(row_strs, separator=',', prefix='', suffix='', formatter={'object':lambda x: x})
                        self.effectStrB += row_str
            if (self.mata.shape != self.matb.shape):
                raise ValueError('Shape of both contrast matrices must be the same')
            return True
        return False

class ChiSqIndModel(RFunction):

    argNames = ['n_row', 'n_col', 'N', 'ns_cells', 'alternative']

    def __init__(self, argNames=argNames, **kwargs):
        super().__init__(name='powerChiSqInd', argNames=argNames, **kwargs)

class ChiSqConModel(RFunction):

    argNames=['pVal', 'mata', 'matb', 'rcomp']

    def __init__(self, argNames=argNames, **kwargs):
        super().__init__(name='powerChiSqCont', argNames=argNames, **kwargs)

# Cell
class ChiSqEstimatesView(HBox, LinkAllMixin):

    def __init__(self, **kwargs):
        super().__init__(layout = ipyw.Layout(width='100%'), **kwargs)

        self.model = ChiSqModel()
        self.ind = ChiSqIndModel()
        self.con = ChiSqIndModel()
        #self.cramers = CorrCramersV(cramersArgNames, kwargs)

        left = VBox(name='left', layout=ipyw.Layout(width='29%'))
        right = VBox(name='right', layout=ipyw.Layout(width='69%'))
        self.children = (left, right)

        ''' left '''
        textarea = Textarea(
            name = 'textarea',
            value = '',
            layout=ipyw.Layout(width="94%", height="150px"),
            disabled=True)
        effectButton = Button(
            name = 'effectButton',
            description='Show effect sizes',
            disabled=False,
            button_style='success',
            layout=ipyw.Layout(min_width='220px', max_width='220px',margin = '2px 2px 2px 2px'))
        effectButton.on_click(self.on_click_effectButton)
        self['left'].children = (textarea, effectButton)

        '''right box'''
        self['right'].children = (RatioEstimatesView(name='ratioEstimatesView', layout=ipyw.Layout(width='100%')), )

        self.link_all(self['right']['ratioEstimatesView'], self.model)
        self.link_all(self['right']['ratioEstimatesView']['colorInts'], self.model)

    def on_click_effectButton(self, button):
        if self.model._color_mats():
            self.run_cramers()
            self['left']['textarea'].value += self.model.effectStrA + ' : ' + self.model.effectStrB + '\n'

    def run_cramers(self):
        """self.cramers.setKwargs(self.model._trait_values)
        self.cramers.run()
        self.model.alternative = self.cramers.results # something in results"""
        pass

    def run(self):
        '''
        if self.model._color_mats():
            self.ind.setDefaultArg
            model = self.ind
        else:
            self.run_cramers()
            model = self.con
        model.setKwargs(self.model._trait_values)

        self.ind.setKwargs(self.model._trait_values)
        result = self.chiSq.run()
        '''