class CompositionWidget(OpenfiscaPluginWidget, Ui_Menage):
    """
    Scenario Graph Widget
    """
    CONF_SECTION = 'composition'
    CONFIGWIDGET_CLASS = CompositionConfigPage
    FEATURES = QDockWidget.DockWidgetClosable | \
        QDockWidget.DockWidgetFloatable | \
        QDockWidget.DockWidgetMovable
    DISABLE_ACTIONS_WHEN_HIDDEN = False
    sig_option_changed = Signal(str, object)
    XAXIS_PROPERTIES = {
        'salaire_imposable': {
            'name': 'salaire_imposable',
            'typ_tot': {
                'salsuperbrut': 'Salaire super brut',
                'salbrut': 'Salaire brut',
                'salaire_imposable': 'Salaire imposable',
                'salaire_net': 'Salaire net'
                },
            'typ_tot_default': 'salaire_imposable',
            },
        'choi': {
            'name': 'cho',
            'col_name': 'choi',
            'typ_tot': {
                'chobrut': u"Chômage brut",
                'cho': u"Chômage",
                'chonet': u"Chômage net",
                },
            'typ_tot_default': 'cho'
            },
        'rsti': {
            'name': 'rst',
            'col_name': 'rsti',
            'typ_tot': {
                'rstbrut': u"Retraite brut",
                'rst': u"Retraite",
                'rstnet': u"Retraite net"
                },
            'typ_tot_default': 'rst'
            },
        'f2da': {
            'name': 'divpfl',
            'col_name': 'f2da',
            'typ_tot': {
                'rev_cap_brut': u"Revenus des capitaux",
                'rev_cap_net': u"Revenus des capitaux nets"
                },
            'typ_tot_default': 'rev_cap_brut',
            },
        'f2ee': {
            'name': 'intpfl',
            'col_name': 'f2ee',
            'typ_tot': {
                'rev_cap_brut': "Revenus des capitaux",
                'rev_cap_net': "Revenus des capitaux nets",
                },
            'typ_tot_default': 'rev_cap_brut'
            },
        'f2dc': {
            'name': 'divb',
            'col_name': 'f2dc',
            'typ_tot': {
                'rev_cap_brut': "Revenus des capitaux",
                'rev_cap_net': "Revenus des capitaux nets"
                },
            'typ_tot_default': 'rev_cap_brut'
            },
        'f2tr': {
            'name': 'intb',
            'col_name': 'f2tr',
            'typ_tot': {
                'rev_cap_brut': "Revenus des capitaux",
                'rev_cap_net': "Revenus des capitaux nets"
                },
            'typ_tot_default': 'rev_cap_brut'
            },
        'pensions_alimentaires_percues': {
            'name': 'pensions_alimentaires_percues',
            'col_name': 'pensions_alimentaires_percues',
            'typ_tot': {
                'pen': "Pensions"
                },
            'typ_tot_default': 'pen'
            },
        'f6gu': {
            'name': 'f6gu',
            'col_name': 'f6gu',
            'typ_tot': {
                'pen': "Pensions"
                },
            'typ_tot_default': 'pen'},
        'f4ba': {
            'name': 'f4ba',
            'col_name': 'f4ba',
            'typ_tot': {
                'fon': "Revenus fonciers"
                },
            'typ_tot_default': 'fon'
        },
    }

    def __init__(self, scenario = None, parent = None):
        super(CompositionWidget, self).__init__(parent)
        self.setupUi(self)
        if parent is not None:
            self.parent = parent

        self.setLayout(self.verticalLayout)
        # Initialize xaxes
        x_axis = self.get_option('x_axis')
        axes_names = []
        for col, axe in self.XAXIS_PROPERTIES.iteritems():
            self.x_axis_box.addItem(col, to_qvariant(axe["name"]))  # convert col to label by using tax_benefit_system
#            self.x_axis_box.addItem(axe.label, to_qvariant(axe.name))
            axes_names.append(axe["name"])
        self.x_axis_box.setCurrentIndex(axes_names.index(x_axis))

        self.initialize_plugin()
        # Initialize maxrev # make it country dependant
        self.maxrev_box.setMinimum(0)
        self.maxrev_box.setMaximum(100000000)
        self.maxrev_box.setSingleStep(1000)
        self.maxrev_box.setSuffix(CURRENCY)
        maxrev = self.get_option('maxrev')
        self.maxrev_box.setValue(maxrev)
        self.maxrev = maxrev

        if scenario is not None:
            self.set_scenario(scenario)

        self.connect(self.open_btn, SIGNAL('clicked()'), self.load)
        self.connect(self.save_btn, SIGNAL('clicked()'), self.save)
        self.connect(self.add_btn, SIGNAL('clicked()'), self.addPerson)
        self.connect(self.rmv_btn, SIGNAL('clicked()'), self.rmvPerson)
        self.connect(self.lgt_btn, SIGNAL('clicked()'), self.openLogement)
        self.connect(self.inf_btn, SIGNAL('clicked()'), self.openInfoComp)
        self.connect(self.reset_btn, SIGNAL('clicked()'), self.resetScenario)
        self.connect(self.x_axis_box, SIGNAL('currentIndexChanged(int)'), self.set_x_axis)
        self.connect(self.maxrev_box, SIGNAL('valueChanged(int)'), self.set_maxrev)
        self.connect(self, SIGNAL('compoChanged()'), self.changed)
        self._listPerson = []
        self.addPref()
        self.rmv_btn.setEnabled(False)
        self.emit(SIGNAL("ok()"))

    #------ Public API ---------------------------------------------

    def set_scenario(self, scenario):
        """
        Set scenario_simualtion
        """
        # TODO fix this
        x_axis = self.get_option('x_axis')
        maxrev = self.maxrev
        nmen = self.get_option('nmen')
        self.nmen = nmen
        value = CONF.get('parameters', 'datesim')
        datesim = datetime.strptime(value, "%Y-%m-%d").date()

        self.scenario = scenario
        self.scenario.year = datesim.year

    def set_x_axis(self):
        '''
        Sets the varying variable of the scenario
        '''
        widget = self.x_axis_box
        if isinstance(widget, QComboBox):
            data = widget.itemData(widget.currentIndex())
            x_axis = unicode(data)
            self.scenario.x_axis = x_axis
            self.set_option('x_axis', x_axis)
        self.emit(SIGNAL('compoChanged()'))

    def set_maxrev(self):
        '''
        Sets the varying variable of the scenario
        '''
        widget = self.maxrev_box

        if isinstance(widget, QSpinBox) or isinstance(widget, QDoubleSpinBox):
            maxrev = widget.value()
            print "in set_maxrev :", maxrev
            self.scenario.maxrev = maxrev
            self.set_option('maxrev', maxrev)
            self.maxrev = maxrev

        self.emit(SIGNAL('compoChanged()'))

    def changed(self):
        self.disconnectAll()
#        self.scenario.genNbEnf()
        self.populate()
        self.action_compute.setEnabled(True)
        self.emit(SIGNAL('changed()'))
        self.connectAll()

    def nbRow(self):
        return self.scenario.nbIndiv()

    def populate(self):
        self.populateBirth()
        self.populateQuifoyCombo()
        self.populateFoyerCombo()
        self.populateQuifamCombo()
        self.populateFamilleCombo()

    def populateBirth(self):
        for noi, vals in self.scenario.indiv.iteritems():
            birth = QDate(vals['birth'])
            self._listPerson[noi][S.birth].setDate(birth)

    def populateFoyerCombo(self):
        declarKeys = self.scenario.declar.keys()
        for noi, vals in self.scenario.indiv.iteritems():
            noidec = vals['noidec']
            box = self._listPerson[noi][S.decnum]
            box.clear()
            button = self._listPerson[noi][S.decbtn]
            button.setText('Foyer %d' % (noidec + 1))
            if vals['quifoy'] == 'vous':
                box.addItems(['%d' % (noidec + 1)])
                button.setEnabled(True)
            else:
                box.addItems(['%d' % (k + 1) for k in declarKeys])
                button.setEnabled(False)
                box.setCurrentIndex(declarKeys.index(noidec))

    def populateQuifoyCombo(self):
        for noi, vals in self.scenario.indiv.iteritems():
            quifoy = vals['quifoy']
            # retrieve the foyer combobox of individu number noi
            box = self._listPerson[noi][S.decpos]
            # set the combobox to 'vous' 'conj' or 'pac'
            if quifoy == 'vous':
                box.setCurrentIndex(0)
            elif quifoy == 'conj':
                box.setCurrentIndex(1)
            elif quifoy[:3] == 'pac':
                box.setCurrentIndex(2)

    def populateFamilleCombo(self):
        familleKeys = self.scenario.famille.keys()
        for noi, vals in self.scenario.indiv.iteritems():
            noichef = vals['noichef']
            box = self._listPerson[noi][S.famnum]
            box.clear()
            if vals['quifam'] == 'parent 1':
                box.addItems(['%d' % (noichef + 1)])
            else:
                box.addItems(['%d' % (k + 1) for k in familleKeys])
                box.setCurrentIndex(familleKeys.index(noichef))

    def populateQuifamCombo(self):
        for noi, vals in self.scenario.indiv.iteritems():
            quifam = vals['quifam']
            # retrieve the foyer combobox of individu number noi
            box = self._listPerson[noi][S.fampos]
            # set the combobox to 'parent 1' 'parent 2' or 'enfant'
            if quifam == 'chef':
                box.setCurrentIndex(0)
            elif quifam == 'part':
                box.setCurrentIndex(1)
            elif quifam[:3] == 'enf':
                box.setCurrentIndex(2)

    def birthChanged(self, date):
        senderNoi = int(self.sender().objectName()[3])
        self.scenario.indiv[senderNoi].update({'birth': date.toPyDate()})
        self.emit(SIGNAL('compoChanged()'))

    def foyerChanged(self):
        sender = self.sender()
        noi = int(sender.objectName()[3])
        newfoyer = int(sender.currentText()[-1]) - 1
        self.scenario.modify(noi, newFoyer = newfoyer)
        self.emit(SIGNAL('compoChanged()'))

    def quifoyChanged(self, newQuifoy):
        senderNoi = int(self.sender().objectName()[3])
        self.scenario.modify(senderNoi, newQuifoy = newQuifoy)
        self.emit(SIGNAL('compoChanged()'))

    def familleChanged(self):
        sender = self.sender()
        noi = int(sender.objectName()[3])
        newfamille = int(sender.currentText()[-1]) - 1
        self.scenario.modifyFam(noi, newFamille = newfamille)
        self.emit(SIGNAL('compoChanged()'))

    def quifamChanged(self, newFam):
        if newFam == 'parent 1':
            qui = 'chef'
        elif newFam == 'parent 2':
            qui = 'part'
        elif newFam == 'enfant':
            qui = 'enf'
        senderNoi = int(self.sender().objectName()[3])
        self.scenario.modifyFam(senderNoi, newQuifam = qui)
        self.emit(SIGNAL('compoChanged()'))

    def addPref(self):
        noi = 0
        self._listPerson.append([QLabel('%d' % (noi + 1), self),
                                 QDateEdit(self),
                                 QComboBox(self),
                                 QComboBox(self),
                                 QPushButton(self),
                                 QComboBox(self),
                                 QComboBox(self)])

        temp = self._listPerson[0]

        temp[S.birth].setDisplayFormat(QApplication.translate("Page01", "dd MMM yyyy", None, QApplication.UnicodeUTF8))
        temp[S.birth].setObjectName('Bir%d' % noi)
        temp[S.birth].setCurrentSection(QDateEdit.YearSection)

        temp[S.decpos].setObjectName('Dec%d' % noi)
        temp[S.decpos].addItems(['vous'])
        temp[S.decpos].setEnabled(False)

        temp[S.decnum].setObjectName('Foy%d' % noi)
        temp[S.decnum].setEnabled(False)

        temp[S.fampos].addItems(['parent 1'])
        temp[S.fampos].setObjectName('Fam%d' % noi)
        temp[S.fampos].setEnabled(False)

        temp[S.famnum].setObjectName('Fam%d' % noi)
        temp[S.famnum].setEnabled(False)

        temp[S.decbtn].setObjectName('But%d' % noi)

        for i in xrange(7):
            self.gridLayout.addWidget(temp[i], noi + 2, i)
            self.gridLayout.setAlignment(temp[i], Qt.AlignCenter)

        self.emit(SIGNAL('compoChanged()'))

    def addPerson(self):
        noi = self.nbRow()
        self.addRow()
        if noi == 1:
            self.scenario.addIndiv(noi, birth = date(1975, 1, 1), quifoy = 'conj', quifam = 'part')
        else:
            self.scenario.addIndiv(noi, birth = date(2000, 1, 1), quifoy = 'pac', quifam = 'enf')
        self.emit(SIGNAL('compoChanged()'))

    def addRow(self):
        noi = len(self._listPerson)
        self._listPerson.append(
            [
                QLabel('%d' % (noi + 1), self),
                QDateEdit(self),
                QComboBox(self),
                QComboBox(self),
                QPushButton(self),
                QComboBox(self),
                QComboBox(self)
                ]
            )
        temp = self._listPerson[-1]

        temp[S.birth].setDisplayFormat(QApplication.translate("Page01", "dd MMM yyyy", None, QApplication.UnicodeUTF8))
        temp[S.birth].setObjectName('Bir%d' % noi)
        temp[S.birth].setCurrentSection(QDateEdit.YearSection)

        temp[S.decpos].setObjectName('Dec%d' % noi)
        temp[S.decpos].addItems(['vous', 'conj', 'pac'])

        temp[S.decnum].setObjectName('Foy%d' % noi)

        temp[S.fampos].setObjectName('Fam%d' % noi)
        temp[S.fampos].addItems(['parent 1', 'parent 2', 'enfant'])

        temp[S.famnum].setObjectName('Fam%d' % noi)

        temp[S.decbtn].setObjectName('But%d' % noi)

        for i in xrange(7):
            self.gridLayout.addWidget(temp[i], noi + 2, i)
            self.gridLayout.setAlignment(temp[i], Qt.AlignCenter)

        self.rmv_btn.setEnabled(True)
        if len(self.scenario.indiv) == 9:
            self.add_btn.setEnabled(False)

    def rmvPerson(self, noi = None):
        if noi is None:
            noi = self.nbRow() - 1
        self.scenario.rmvIndiv(noi)
        self.rmvRow()
        self.add_btn.setEnabled(True)

        self.emit(SIGNAL('compoChanged()'))

    def rmvRow(self):
        '''
        Enlève le dernier individu et l'efface dans le foyer
        '''
        toDel = self._listPerson.pop()
        for widget in toDel:
            widget.setParent(None)
        if len(self.scenario.indiv) == 1:
            self.rmv_btn.setEnabled(False)

    def resetScenario(self):
        '''
        Resets scenario
        '''
        while self.nbRow() > 1:
            self.rmvPerson()
        self.simulation.reset_scenario
        self.emit(SIGNAL('compoChanged()'))

    def openDeclaration(self):
        """
        Open the declaration widget
        """
        noi = int(self.sender().objectName()[3])
        self.scenario.genNbEnf()
        msg = self.scenario.check_consistency()
        if msg:
            QMessageBox.critical(self, u"Ménage non valide",
                                 msg,
                                 QMessageBox.Ok, QMessageBox.NoButton)
            return False
        self._declaration = Declaration(self, noi)
        self._declaration.exec_()
        self.emit(SIGNAL('compoChanged()'))

    def openLogement(self):
        self._logement = Logement(self.scenario, self)
        self._logement.exec_()
        self.emit(SIGNAL('compoChanged()'))

    def openInfoComp(self):
        self._infocomp = InfoComp(self.scenario, self)
        self._infocomp.exec_()
        self.emit(SIGNAL('compoChanged()'))

    def disconnectAll(self):
        for person in self._listPerson:
            QObject.disconnect(person[S.birth], SIGNAL('dateChanged(QDate)'), self.birthChanged)
            QObject.disconnect(person[S.decpos], SIGNAL('currentIndexChanged(QString)'), self.quifoyChanged)
            QObject.disconnect(person[S.decnum], SIGNAL('currentIndexChanged(int)'), self.foyerChanged)
            QObject.disconnect(person[S.fampos], SIGNAL('currentIndexChanged(QString)'), self.quifamChanged)
            QObject.disconnect(person[S.famnum], SIGNAL('currentIndexChanged(int)'), self.familleChanged)
            QObject.disconnect(person[S.decbtn], SIGNAL('clicked()'), self.openDeclaration)

    def connectAll(self):
        for person in self._listPerson:
            QObject.connect(person[S.birth], SIGNAL('dateChanged(QDate)'), self.birthChanged)
            QObject.connect(person[S.decpos], SIGNAL('currentIndexChanged(QString)'), self.quifoyChanged)
            QObject.connect(person[S.decnum], SIGNAL('currentIndexChanged(int)'), self.foyerChanged)
            QObject.connect(person[S.fampos], SIGNAL('currentIndexChanged(QString)'), self.quifamChanged)
            QObject.connect(person[S.famnum], SIGNAL('currentIndexChanged(int)'), self.familleChanged)
            QObject.connect(person[S.decbtn], SIGNAL('clicked()'), self.openDeclaration)

    def load(self):
        cas_type_dir = self.get_option('import_dir')
        fileName = QFileDialog.getOpenFileName(self,
                                               _("Open a test case"),
                                               cas_type_dir,
                                               u"Cas type OpenFisca (*.ofct)")
        if not fileName == '':
            n = len(self.scenario.indiv)
            try:
                self.scenario.openFile(fileName)
                while n < self.nbRow():
                    self.addRow()
                    n += 1
                while n > self.nbRow():
                    self.rmvRow()
                    n -= 1
                self.emit(SIGNAL('compoChanged()'))
                self.emit(SIGNAL("ok()"))
            except Exception, e:
                QMessageBox.critical(
                    self, "Erreur", u"Erreur lors de l'ouverture du fichier : le fichier n'est pas reconnu : \n " + e,
                    QMessageBox.Ok, QMessageBox.NoButton)
class CompositionWidget(OpenfiscaPluginWidget, Ui_Menage):
    """
    Scenario Graph Widget
    """
    CONF_SECTION = 'composition'
    CONFIGWIDGET_CLASS = CompositionConfigPage
    FEATURES = QDockWidget.DockWidgetClosable | \
        QDockWidget.DockWidgetFloatable | \
        QDockWidget.DockWidgetMovable
    DISABLE_ACTIONS_WHEN_HIDDEN = False
    sig_option_changed = Signal(str, object)
    XAXIS_PROPERTIES = {
        'sali': {
            'name': 'sal',
            'typ_tot': {
                'salsuperbrut': 'Salaire super brut',
                'salbrut': 'Salaire brut',
                'sal': 'Salaire imposable',
                'salnet': 'Salaire net'
            },
            'typ_tot_default': 'sal',
        },
        'choi': {
            'name': 'cho',
            'col_name': 'choi',
            'typ_tot': {
                'chobrut': u"Chômage brut",
                'cho': u"Chômage",
                'chonet': u"Chômage net",
            },
            'typ_tot_default': 'cho'
        },
        'rsti': {
            'name': 'rst',
            'col_name': 'rsti',
            'typ_tot': {
                'rstbrut': u"Retraite brut",
                'rst': u"Retraite",
                'rstnet': u"Retraite net"
            },
            'typ_tot_default': 'rst'
        },
        'f2da': {
            'name': 'divpfl',
            'col_name': 'f2da',
            'typ_tot': {
                'rev_cap_brut': u"Revenus des capitaux",
                'rev_cap_net': u"Revenus des capitaux nets"
            },
            'typ_tot_default': 'rev_cap_brut',
        },
        'f2ee': {
            'name': 'intpfl',
            'col_name': 'f2ee',
            'typ_tot': {
                'rev_cap_brut': "Revenus des capitaux",
                'rev_cap_net': "Revenus des capitaux nets",
            },
            'typ_tot_default': 'rev_cap_brut'
        },
        'f2dc': {
            'name': 'divb',
            'col_name': 'f2dc',
            'typ_tot': {
                'rev_cap_brut': "Revenus des capitaux",
                'rev_cap_net': "Revenus des capitaux nets"
            },
            'typ_tot_default': 'rev_cap_brut'
        },
        'f2tr': {
            'name': 'intb',
            'col_name': 'f2tr',
            'typ_tot': {
                'rev_cap_brut': "Revenus des capitaux",
                'rev_cap_net': "Revenus des capitaux nets"
            },
            'typ_tot_default': 'rev_cap_brut'
        },
        'alr': {
            'name': 'alr',
            'col_name': 'alr',
            'typ_tot': {
                'pen': "Pensions"
            },
            'typ_tot_default': 'pen'
        },
        'f6gu': {
            'name': 'f6gu',
            'col_name': 'f6gu',
            'typ_tot': {
                'pen': "Pensions"
            },
            'typ_tot_default': 'pen'
        },
        'f4ba': {
            'name': 'f4ba',
            'col_name': 'f4ba',
            'typ_tot': {
                'fon': "Revenus fonciers"
            },
            'typ_tot_default': 'fon'
        },
    }

    def __init__(self, scenario=None, parent=None):
        super(CompositionWidget, self).__init__(parent)
        self.setupUi(self)
        if parent is not None:
            self.parent = parent

        self.setLayout(self.verticalLayout)
        # Initialize xaxes
        x_axis = self.get_option('x_axis')
        axes_names = []
        for col, axe in self.XAXIS_PROPERTIES.iteritems():
            self.x_axis_box.addItem(
                col, to_qvariant(axe["name"])
            )  # convert col to label by using tax_benefit_system
            #            self.x_axis_box.addItem(axe.label, to_qvariant(axe.name))
            axes_names.append(axe["name"])
        self.x_axis_box.setCurrentIndex(axes_names.index(x_axis))

        self.initialize_plugin()
        # Initialize maxrev # make it country dependant
        self.maxrev_box.setMinimum(0)
        self.maxrev_box.setMaximum(100000000)
        self.maxrev_box.setSingleStep(1000)
        self.maxrev_box.setSuffix(CURRENCY)
        maxrev = self.get_option('maxrev')
        self.maxrev_box.setValue(maxrev)
        self.maxrev = maxrev

        if scenario is not None:
            self.set_scenario(scenario)

        self.connect(self.open_btn, SIGNAL('clicked()'), self.load)
        self.connect(self.save_btn, SIGNAL('clicked()'), self.save)
        self.connect(self.add_btn, SIGNAL('clicked()'), self.addPerson)
        self.connect(self.rmv_btn, SIGNAL('clicked()'), self.rmvPerson)
        self.connect(self.lgt_btn, SIGNAL('clicked()'), self.openLogement)
        self.connect(self.inf_btn, SIGNAL('clicked()'), self.openInfoComp)
        self.connect(self.reset_btn, SIGNAL('clicked()'), self.resetScenario)
        self.connect(self.x_axis_box, SIGNAL('currentIndexChanged(int)'),
                     self.set_x_axis)
        self.connect(self.maxrev_box, SIGNAL('valueChanged(int)'),
                     self.set_maxrev)
        self.connect(self, SIGNAL('compoChanged()'), self.changed)
        self._listPerson = []
        self.addPref()
        self.rmv_btn.setEnabled(False)
        self.emit(SIGNAL("ok()"))

    #------ Public API ---------------------------------------------

    def set_scenario(self, scenario):
        """
        Set scenario_simualtion
        """
        # TODO fix this
        x_axis = self.get_option('x_axis')
        maxrev = self.maxrev
        nmen = self.get_option('nmen')
        self.nmen = nmen
        value = CONF.get('parameters', 'datesim')
        datesim = datetime.strptime(value, "%Y-%m-%d").date()

        self.scenario = scenario
        self.scenario.year = datesim.year

    def set_x_axis(self):
        '''
        Sets the varying variable of the scenario
        '''
        widget = self.x_axis_box
        if isinstance(widget, QComboBox):
            data = widget.itemData(widget.currentIndex())
            x_axis = unicode(data)
            self.scenario.x_axis = x_axis
            self.set_option('x_axis', x_axis)
        self.emit(SIGNAL('compoChanged()'))

    def set_maxrev(self):
        '''
        Sets the varying variable of the scenario
        '''
        widget = self.maxrev_box

        if isinstance(widget, QSpinBox) or isinstance(widget, QDoubleSpinBox):
            maxrev = widget.value()
            print "in set_maxrev :", maxrev
            self.scenario.maxrev = maxrev
            self.set_option('maxrev', maxrev)
            self.maxrev = maxrev

        self.emit(SIGNAL('compoChanged()'))

    def changed(self):
        self.disconnectAll()
        #        self.scenario.genNbEnf()
        self.populate()
        self.action_compute.setEnabled(True)
        self.emit(SIGNAL('changed()'))
        self.connectAll()

    def nbRow(self):
        return self.scenario.nbIndiv()

    def populate(self):
        self.populateBirth()
        self.populateQuifoyCombo()
        self.populateFoyerCombo()
        self.populateQuifamCombo()
        self.populateFamilleCombo()

    def populateBirth(self):
        for noi, vals in self.scenario.indiv.iteritems():
            birth = QDate(vals['birth'])
            self._listPerson[noi][S.birth].setDate(birth)

    def populateFoyerCombo(self):
        declarKeys = self.scenario.declar.keys()
        for noi, vals in self.scenario.indiv.iteritems():
            noidec = vals['noidec']
            box = self._listPerson[noi][S.decnum]
            box.clear()
            button = self._listPerson[noi][S.decbtn]
            button.setText('Foyer %d' % (noidec + 1))
            if vals['quifoy'] == 'vous':
                box.addItems(['%d' % (noidec + 1)])
                button.setEnabled(True)
            else:
                box.addItems(['%d' % (k + 1) for k in declarKeys])
                button.setEnabled(False)
                box.setCurrentIndex(declarKeys.index(noidec))

    def populateQuifoyCombo(self):
        for noi, vals in self.scenario.indiv.iteritems():
            quifoy = vals['quifoy']
            # retrieve the foyer combobox of individu number noi
            box = self._listPerson[noi][S.decpos]
            # set the combobox to 'vous' 'conj' or 'pac'
            if quifoy == 'vous':
                box.setCurrentIndex(0)
            elif quifoy == 'conj':
                box.setCurrentIndex(1)
            elif quifoy[:3] == 'pac':
                box.setCurrentIndex(2)

    def populateFamilleCombo(self):
        familleKeys = self.scenario.famille.keys()
        for noi, vals in self.scenario.indiv.iteritems():
            noichef = vals['noichef']
            box = self._listPerson[noi][S.famnum]
            box.clear()
            if vals['quifam'] == 'parent 1':
                box.addItems(['%d' % (noichef + 1)])
            else:
                box.addItems(['%d' % (k + 1) for k in familleKeys])
                box.setCurrentIndex(familleKeys.index(noichef))

    def populateQuifamCombo(self):
        for noi, vals in self.scenario.indiv.iteritems():
            quifam = vals['quifam']
            # retrieve the foyer combobox of individu number noi
            box = self._listPerson[noi][S.fampos]
            # set the combobox to 'parent 1' 'parent 2' or 'enfant'
            if quifam == 'chef':
                box.setCurrentIndex(0)
            elif quifam == 'part':
                box.setCurrentIndex(1)
            elif quifam[:3] == 'enf':
                box.setCurrentIndex(2)

    def birthChanged(self, date):
        senderNoi = int(self.sender().objectName()[3])
        self.scenario.indiv[senderNoi].update({'birth': date.toPyDate()})
        self.emit(SIGNAL('compoChanged()'))

    def foyerChanged(self):
        sender = self.sender()
        noi = int(sender.objectName()[3])
        newfoyer = int(sender.currentText()[-1]) - 1
        self.scenario.modify(noi, newFoyer=newfoyer)
        self.emit(SIGNAL('compoChanged()'))

    def quifoyChanged(self, newQuifoy):
        senderNoi = int(self.sender().objectName()[3])
        self.scenario.modify(senderNoi, newQuifoy=newQuifoy)
        self.emit(SIGNAL('compoChanged()'))

    def familleChanged(self):
        sender = self.sender()
        noi = int(sender.objectName()[3])
        newfamille = int(sender.currentText()[-1]) - 1
        self.scenario.modifyFam(noi, newFamille=newfamille)
        self.emit(SIGNAL('compoChanged()'))

    def quifamChanged(self, newFam):
        if newFam == 'parent 1':
            qui = 'chef'
        elif newFam == 'parent 2':
            qui = 'part'
        elif newFam == 'enfant':
            qui = 'enf'
        senderNoi = int(self.sender().objectName()[3])
        self.scenario.modifyFam(senderNoi, newQuifam=qui)
        self.emit(SIGNAL('compoChanged()'))

    def addPref(self):
        noi = 0
        self._listPerson.append([
            QLabel('%d' % (noi + 1), self),
            QDateEdit(self),
            QComboBox(self),
            QComboBox(self),
            QPushButton(self),
            QComboBox(self),
            QComboBox(self)
        ])

        temp = self._listPerson[0]

        temp[S.birth].setDisplayFormat(
            QApplication.translate("Page01", "dd MMM yyyy", None,
                                   QApplication.UnicodeUTF8))
        temp[S.birth].setObjectName('Bir%d' % noi)
        temp[S.birth].setCurrentSection(QDateEdit.YearSection)

        temp[S.decpos].setObjectName('Dec%d' % noi)
        temp[S.decpos].addItems(['vous'])
        temp[S.decpos].setEnabled(False)

        temp[S.decnum].setObjectName('Foy%d' % noi)
        temp[S.decnum].setEnabled(False)

        temp[S.fampos].addItems(['parent 1'])
        temp[S.fampos].setObjectName('Fam%d' % noi)
        temp[S.fampos].setEnabled(False)

        temp[S.famnum].setObjectName('Fam%d' % noi)
        temp[S.famnum].setEnabled(False)

        temp[S.decbtn].setObjectName('But%d' % noi)

        for i in xrange(7):
            self.gridLayout.addWidget(temp[i], noi + 2, i)
            self.gridLayout.setAlignment(temp[i], Qt.AlignCenter)

        self.emit(SIGNAL('compoChanged()'))

    def addPerson(self):
        noi = self.nbRow()
        self.addRow()
        if noi == 1:
            self.scenario.addIndiv(noi,
                                   birth=date(1975, 1, 1),
                                   quifoy='conj',
                                   quifam='part')
        else:
            self.scenario.addIndiv(noi,
                                   birth=date(2000, 1, 1),
                                   quifoy='pac',
                                   quifam='enf')
        self.emit(SIGNAL('compoChanged()'))

    def addRow(self):
        noi = len(self._listPerson)
        self._listPerson.append([
            QLabel('%d' % (noi + 1), self),
            QDateEdit(self),
            QComboBox(self),
            QComboBox(self),
            QPushButton(self),
            QComboBox(self),
            QComboBox(self)
        ])
        temp = self._listPerson[-1]

        temp[S.birth].setDisplayFormat(
            QApplication.translate("Page01", "dd MMM yyyy", None,
                                   QApplication.UnicodeUTF8))
        temp[S.birth].setObjectName('Bir%d' % noi)
        temp[S.birth].setCurrentSection(QDateEdit.YearSection)

        temp[S.decpos].setObjectName('Dec%d' % noi)
        temp[S.decpos].addItems(['vous', 'conj', 'pac'])

        temp[S.decnum].setObjectName('Foy%d' % noi)

        temp[S.fampos].setObjectName('Fam%d' % noi)
        temp[S.fampos].addItems(['parent 1', 'parent 2', 'enfant'])

        temp[S.famnum].setObjectName('Fam%d' % noi)

        temp[S.decbtn].setObjectName('But%d' % noi)

        for i in xrange(7):
            self.gridLayout.addWidget(temp[i], noi + 2, i)
            self.gridLayout.setAlignment(temp[i], Qt.AlignCenter)

        self.rmv_btn.setEnabled(True)
        if len(self.scenario.indiv) == 9:
            self.add_btn.setEnabled(False)

    def rmvPerson(self, noi=None):
        if noi is None:
            noi = self.nbRow() - 1
        self.scenario.rmvIndiv(noi)
        self.rmvRow()
        self.add_btn.setEnabled(True)

        self.emit(SIGNAL('compoChanged()'))

    def rmvRow(self):
        '''
        Enlève le dernier individu et l'efface dans le foyer
        '''
        toDel = self._listPerson.pop()
        for widget in toDel:
            widget.setParent(None)
        if len(self.scenario.indiv) == 1:
            self.rmv_btn.setEnabled(False)

    def resetScenario(self):
        '''
        Resets scenario
        '''
        while self.nbRow() > 1:
            self.rmvPerson()
        self.simulation.reset_scenario
        self.emit(SIGNAL('compoChanged()'))

    def openDeclaration(self):
        """
        Open the declaration widget
        """
        noi = int(self.sender().objectName()[3])
        self.scenario.genNbEnf()
        msg = self.scenario.check_consistency()
        if msg:
            QMessageBox.critical(self, u"Ménage non valide", msg,
                                 QMessageBox.Ok, QMessageBox.NoButton)
            return False
        self._declaration = Declaration(self, noi)
        self._declaration.exec_()
        self.emit(SIGNAL('compoChanged()'))

    def openLogement(self):
        self._logement = Logement(self.scenario, self)
        self._logement.exec_()
        self.emit(SIGNAL('compoChanged()'))

    def openInfoComp(self):
        self._infocomp = InfoComp(self.scenario, self)
        self._infocomp.exec_()
        self.emit(SIGNAL('compoChanged()'))

    def disconnectAll(self):
        for person in self._listPerson:
            QObject.disconnect(person[S.birth], SIGNAL('dateChanged(QDate)'),
                               self.birthChanged)
            QObject.disconnect(person[S.decpos],
                               SIGNAL('currentIndexChanged(QString)'),
                               self.quifoyChanged)
            QObject.disconnect(person[S.decnum],
                               SIGNAL('currentIndexChanged(int)'),
                               self.foyerChanged)
            QObject.disconnect(person[S.fampos],
                               SIGNAL('currentIndexChanged(QString)'),
                               self.quifamChanged)
            QObject.disconnect(person[S.famnum],
                               SIGNAL('currentIndexChanged(int)'),
                               self.familleChanged)
            QObject.disconnect(person[S.decbtn], SIGNAL('clicked()'),
                               self.openDeclaration)

    def connectAll(self):
        for person in self._listPerson:
            QObject.connect(person[S.birth], SIGNAL('dateChanged(QDate)'),
                            self.birthChanged)
            QObject.connect(person[S.decpos],
                            SIGNAL('currentIndexChanged(QString)'),
                            self.quifoyChanged)
            QObject.connect(person[S.decnum],
                            SIGNAL('currentIndexChanged(int)'),
                            self.foyerChanged)
            QObject.connect(person[S.fampos],
                            SIGNAL('currentIndexChanged(QString)'),
                            self.quifamChanged)
            QObject.connect(person[S.famnum],
                            SIGNAL('currentIndexChanged(int)'),
                            self.familleChanged)
            QObject.connect(person[S.decbtn], SIGNAL('clicked()'),
                            self.openDeclaration)

    def load(self):
        cas_type_dir = self.get_option('import_dir')
        fileName = QFileDialog.getOpenFileName(self, _("Open a test case"),
                                               cas_type_dir,
                                               u"Cas type OpenFisca (*.ofct)")
        if not fileName == '':
            n = len(self.scenario.indiv)
            try:
                self.scenario.openFile(fileName)
                while n < self.nbRow():
                    self.addRow()
                    n += 1
                while n > self.nbRow():
                    self.rmvRow()
                    n -= 1
                self.emit(SIGNAL('compoChanged()'))
                self.emit(SIGNAL("ok()"))
            except Exception, e:
                QMessageBox.critical(
                    self, "Erreur",
                    u"Erreur lors de l'ouverture du fichier : le fichier n'est pas reconnu : \n "
                    + e, QMessageBox.Ok, QMessageBox.NoButton)
 def openInfoComp(self):
     self._infocomp = InfoComp(self.scenario, self)
     self._infocomp.exec_()
     self.emit(SIGNAL('compoChanged()'))
 def openInfoComp(self):
     self._infocomp = InfoComp(self.scenario, self)
     self._infocomp.exec_()
     self.emit(SIGNAL('compoChanged()'))