class frmInfiltration(QtGui.QMainWindow, Ui_frmInfiltrationEditor):
    def __init__(self, parent, edit_these, title):
        QtGui.QMainWindow.__init__(self, parent)
        self.helper = HelpHandler(self)
        option_section = parent.project.find_section('OPTIONS')
        if option_section.infiltration == "HORTON" or option_section.infiltration == "MODIFIED_HORTON":
            self.help_topic = "swmm/src/src/hortoninfiltrationparameters.htm"
        elif option_section.infiltration == "GREEN_AMPT" or option_section.infiltration == "MODIFIED_GREEN_AMPT":
            self.help_topic = "swmm/src/src/green_amptinfiltrationparame.htm"
        elif option_section.infiltration == "CURVE_NUMBER":
            self.help_topic = "swmm/src/src/curvenumberinfiltrationpara.htm"
        self.setupUi(self)
        self.setWindowTitle(title)
        QtCore.QObject.connect(self.cmdOK, QtCore.SIGNAL("clicked()"),
                               self.cmdOK_Clicked)
        QtCore.QObject.connect(self.cmdCancel, QtCore.SIGNAL("clicked()"),
                               self.cmdCancel_Clicked)
        self.backend = PropertyEditorBackend(self.tblGeneric, self.lblNotes,
                                             parent, edit_these)
        self.lblTop.setText(
            "Infiltration Method:  " +
            parent.project.find_section('OPTIONS').infiltration)
        # self.tblGeneric.horizontalHeader().show()
        # self.tblGeneric.setHorizontalHeaderLabels(('1','2','3','4','5','6','7','8'))

    def cmdOK_Clicked(self):
        self.backend.apply_edits()
        self.close()

    def cmdCancel_Clicked(self):
        self.close()
    def __init__(self, main_form, edit_these, new_item, title):
        QMainWindow.__init__(self, main_form)
        self.helper = HelpHandler(self)
        self.help_topic = "swmm/src/src/groundwaterfloweditordialog.htm"
        self._main_form = main_form
        self.project = main_form.project
        self.new_item = new_item
        self.refresh_column = -1
        self.setupUi(self)
        self.setWindowTitle(title)
        self.cmdOK.clicked.connect(self.cmdOK_Clicked)
        self.cmdCancel.clicked.connect(self.cmdCancel_Clicked)
        self.backend = PropertyEditorBackend(self.tblGeneric, self.lblNotes,
                                             main_form, edit_these, new_item)

        for column in range(0, self.tblGeneric.columnCount()):
            # for aquifers, show available aquifers
            aquifer_section = main_form.project.find_section("AQUIFERS")
            aquifer_list = aquifer_section.value[0:]
            combobox = QComboBox()
            combobox.addItem('')
            selected_index = 0
            for value in aquifer_list:
                combobox.addItem(value.name)
                if edit_these[column].aquifer == value.name:
                    selected_index = int(combobox.count()) - 1
            combobox.setCurrentIndex(selected_index)
            self.tblGeneric.setCellWidget(1, column, combobox)
            # also set special text plus button cells
            self.set_lateral_equation(column)
            self.set_deep_equation(column)

        self.installEventFilter(self)
    def __init__(self, parent, edit_these, new_item, title, **kwargs):
        QtGui.QMainWindow.__init__(self, parent)
        self.helper = HelpHandler(self)
        option_section = parent.project.find_section('OPTIONS')
        if option_section.infiltration=="HORTON" or option_section.infiltration=="MODIFIED_HORTON":
            self.help_topic = "swmm/src/src/hortoninfiltrationparameters.htm"
        elif option_section.infiltration=="GREEN_AMPT" or option_section.infiltration=="MODIFIED_GREEN_AMPT":
            self.help_topic = "swmm/src/src/green_amptinfiltrationparame.htm"
        elif option_section.infiltration=="CURVE_NUMBER":
            self.help_topic = "swmm/src/src/curvenumberinfiltrationpara.htm"
        self.setupUi(self)
        self.setWindowTitle(title)
        QtCore.QObject.connect(self.cmdOK, QtCore.SIGNAL("clicked()"), self.cmdOK_Clicked)
        QtCore.QObject.connect(self.cmdCancel, QtCore.SIGNAL("clicked()"), self.cmdCancel_Clicked)
        QtCore.QObject.connect(self.cboInfilModel, QtCore.SIGNAL("currentIndexChanged(int)"),
                               self.cboInfilModel_currentIndexChanged)

        self.defaults = None
        if kwargs.has_key("defaults"):
            self.defaults = kwargs["defaults"]
        enum_val = E_InfilModel.HORTON
        if self.defaults is not None:
            enum_val = E_InfilModel[self.defaults.properties_sub_values[self.defaults.infil_model_key]]
            # self.infil_model = self.qsettings.value(self.default_key, None)
            # if self.infil_model is None:
            #     self.infil_model = HortonInfiltration()
            #     self.infil_model.set_defaults()
            # else:
            #     enum_val = self.infil_model.model_type()
            #     if enum_val == E_InfilModel.HORTON or \
            #        enum_val == E_InfilModel.MODIFIED_HORTON:
            #         self.infil_model_horton.__dict__.update(self.infil_model.__dict__)
            #     elif enum_val == E_InfilModel.GREEN_AMPT or \
            #          enum_val == E_InfilModel.MODIFIED_GREEN_AMPT:
            #         self.infil_model_ga.__dict__.update(self.infil_model.__dict__)
            #     elif enum_val == E_InfilModel.CURVE_NUMBER:
            #         self.infil_model_cn.__dict__.update(self.infil_model.__dict__)

            self.cboInfilModel.setEnabled(True)
            if self.lblNotes:
                self.tblGeneric.currentCellChanged.connect(self.table_currentCellChanged)
            self.tblGeneric.itemChanged.connect(self.table_itemChanged)
            pass
        else:
            self.backend = PropertyEditorBackend(self.tblGeneric, self.lblNotes, parent, edit_these, new_item)
            #self.lblTop.setText("Infiltration Method:  " + parent.project.find_section('OPTIONS').infiltration)
            proj_infilmodel = parent.project.find_section('OPTIONS').infiltration
            enum_val = E_InfilModel[proj_infilmodel.upper()]
            self.cboInfilModel.setEnabled(False)

        set_combo_items(type(enum_val), self.cboInfilModel)
        set_combo(self.cboInfilModel, enum_val)

        self.corner_label = QtGui.QLabel("Property", self.tblGeneric)
        self.corner_label.setAlignment(QtCore.Qt.AlignCenter)
        self.corner_label.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)
        QtCore.QObject.connect(self.tblGeneric.verticalHeader(),
                               QtCore.SIGNAL("geometriesChanged()"), self.resizeCorner)
        QtCore.QObject.connect(self.tblGeneric.horizontalHeader(),
                               QtCore.SIGNAL("geometriesChanged()"), self.resizeCorner)
    def __init__(self, main_form, edit_these, title):
        QtGui.QMainWindow.__init__(self, main_form)
        self.helper = HelpHandler(self)
        self.help_topic = "swmm/src/src/groundwaterfloweditordialog.htm"
        self._main_form = main_form
        self.project = main_form.project
        self.refresh_column = -1
        self.setupUi(self)
        self.setWindowTitle(title)
        QtCore.QObject.connect(self.cmdOK, QtCore.SIGNAL("clicked()"), self.cmdOK_Clicked)
        QtCore.QObject.connect(self.cmdCancel, QtCore.SIGNAL("clicked()"), self.cmdCancel_Clicked)
        self.backend = PropertyEditorBackend(self.tblGeneric, self.lblNotes, main_form, edit_these)

        for column in range(0, self.tblGeneric.columnCount()):
            # for aquifers, show available aquifers
            aquifer_section = main_form.project.find_section("AQUIFERS")
            aquifer_list = aquifer_section.value[0:]
            combobox = QtGui.QComboBox()
            combobox.addItem('')
            selected_index = 0
            for value in aquifer_list:
                combobox.addItem(value.name)
                if edit_these[column].aquifer == value.name:
                    selected_index = int(combobox.count())-1
            combobox.setCurrentIndex(selected_index)
            self.tblGeneric.setCellWidget(1, column, combobox)
            # also set special text plus button cells
            self.set_lateral_equation(column)
            self.set_deep_equation(column)

        self.installEventFilter(self)
    def __init__(self, session, project_section, edit_these, new_item, title):
        QMainWindow.__init__(self, session)
        self.setupUi(self)
        self.setWindowTitle(title)
        self.cmdOK.clicked.connect(self.cmdOK_Clicked)
        self.cmdCancel.clicked.connect(self.cmdCancel_Clicked)

        self.session = session
        self.project = session.project
        self.project_section = project_section
        if new_item:
            edit_these = [new_item]
        elif self.project_section and \
                isinstance(self.project_section.value, list) and \
                len(self.project_section.value) > 0 and \
                (not hasattr(self, "SECTION_TYPE") or isinstance(self.project_section.value[0], self.SECTION_TYPE)):

            if edit_these:  # Edit only specified item(s) in section
                if isinstance(edit_these[0], str):  # Translate list from names to objects
                    edit_names = edit_these
                    edit_objects = [item for item in self.project_section.value if item.name in edit_these]
                    edit_these = edit_objects

            else:  # Edit all items in section
                edit_these = []
                edit_these.extend(self.project_section.value)
        self.edit_these = edit_these
        self.backend = PropertyEditorBackend(self.tblGeneric, self.lblNotes, session, edit_these, new_item)
        self.tblGeneric.cellChanged.connect(self.check_change)
        for row in range(self.tblGeneric.rowCount()):
            self.tblGeneric.setRowHeight(row, 20)

        self._main_form = session
        if session.model == 'SWMM':
            if project_section.SECTION_NAME == '[LABELS]' or project_section.SECTION_NAME == '[POLLUTANTS]':
                word = project_section.SECTION_NAME.strip('[]')

                if (session.program_settings.value("Geometry/" + "frmGenericPropertyEditor_" + word + "_geometry") and
                        session.program_settings.value("Geometry/" + "frmGenericPropertyEditor_" + word + "_state")):
                    self.restoreGeometry(
                        session.program_settings.value("Geometry/" + "frmGenericPropertyEditor_" + word +
                                                       "_geometry", self.geometry(), type=QtCore.QByteArray))
                    self.restoreState(
                        session.program_settings.value("Geometry/" + "frmGenericPropertyEditor_" + word +
                                                       "_state", self.windowState(), type=QtCore.QByteArray))
 def __init__(self, parent, edit_these, title):
     QtGui.QMainWindow.__init__(self, parent)
     self.helper = HelpHandler(self)
     option_section = parent.project.find_section('OPTIONS')
     if option_section.infiltration == "HORTON" or option_section.infiltration == "MODIFIED_HORTON":
         self.help_topic = "swmm/src/src/hortoninfiltrationparameters.htm"
     elif option_section.infiltration == "GREEN_AMPT" or option_section.infiltration == "MODIFIED_GREEN_AMPT":
         self.help_topic = "swmm/src/src/green_amptinfiltrationparame.htm"
     elif option_section.infiltration == "CURVE_NUMBER":
         self.help_topic = "swmm/src/src/curvenumberinfiltrationpara.htm"
     self.setupUi(self)
     self.setWindowTitle(title)
     QtCore.QObject.connect(self.cmdOK, QtCore.SIGNAL("clicked()"),
                            self.cmdOK_Clicked)
     QtCore.QObject.connect(self.cmdCancel, QtCore.SIGNAL("clicked()"),
                            self.cmdCancel_Clicked)
     self.backend = PropertyEditorBackend(self.tblGeneric, self.lblNotes,
                                          parent, edit_these)
     self.lblTop.setText(
         "Infiltration Method:  " +
         parent.project.find_section('OPTIONS').infiltration)
    def __init__(self, session, project_section, edit_these, new_item, title):
        QMainWindow.__init__(self, session)
        self.setupUi(self)
        self.setWindowTitle(title)
        self.cmdOK.clicked.connect(self.cmdOK_Clicked)
        self.cmdCancel.clicked.connect(self.cmdCancel_Clicked)

        self.session = session
        self.project = session.project
        self.project_section = project_section
        if new_item:
            edit_these = [new_item]
        elif self.project_section and \
                isinstance(self.project_section.value, list) and \
                len(self.project_section.value) > 0 and \
                (not hasattr(self, "SECTION_TYPE") or isinstance(self.project_section.value[0], self.SECTION_TYPE)):

            if edit_these:  # Edit only specified item(s) in section
                if isinstance(edit_these[0],
                              str):  # Translate list from names to objects
                    edit_names = edit_these
                    edit_objects = [
                        item for item in self.project_section.value
                        if item.name in edit_these
                    ]
                    edit_these = edit_objects

            else:  # Edit all items in section
                edit_these = []
                edit_these.extend(self.project_section.value)
        self.edit_these = edit_these
        self.backend = PropertyEditorBackend(self.tblGeneric, self.lblNotes,
                                             session, edit_these, new_item)
        self.tblGeneric.cellChanged.connect(self.check_change)
        for row in range(self.tblGeneric.rowCount()):
            self.tblGeneric.setRowHeight(row, 20)
class frmGroundwaterFlow(QMainWindow, Ui_frmGroundwaterFlow):
    def __init__(self, main_form, edit_these, new_item, title):
        QMainWindow.__init__(self, main_form)
        self.helper = HelpHandler(self)
        self.help_topic = "swmm/src/src/groundwaterfloweditordialog.htm"
        self._main_form = main_form
        self.project = main_form.project
        self.new_item = new_item
        self.refresh_column = -1
        self.setupUi(self)
        self.setWindowTitle(title)
        self.cmdOK.clicked.connect(self.cmdOK_Clicked)
        self.cmdCancel.clicked.connect(self.cmdCancel_Clicked)
        self.backend = PropertyEditorBackend(self.tblGeneric, self.lblNotes,
                                             main_form, edit_these, new_item)

        for column in range(0, self.tblGeneric.columnCount()):
            # for aquifers, show available aquifers
            aquifer_section = main_form.project.find_section("AQUIFERS")
            aquifer_list = aquifer_section.value[0:]
            combobox = QComboBox()
            combobox.addItem('')
            selected_index = 0
            for value in aquifer_list:
                combobox.addItem(value.name)
                if edit_these[column].aquifer == value.name:
                    selected_index = int(combobox.count()) - 1
            combobox.setCurrentIndex(selected_index)
            self.tblGeneric.setCellWidget(1, column, combobox)
            # also set special text plus button cells
            self.set_lateral_equation(column)
            self.set_deep_equation(column)

        self.installEventFilter(self)

    def eventFilter(self, ui_object, event):
        if event.type() == QtCore.QEvent.WindowUnblocked:
            if self.refresh_column > -1:
                self.set_lateral_equation(self.refresh_column)
                self.set_deep_equation(self.refresh_column)
                self.refresh_column = -1
        return False

    def set_lateral_equation(self, column):
        # text plus button for custom lateral equation
        tb = TextPlusButton(self)
        tb.textbox.setText('NO')
        groundwater_section = self.project.groundwater
        groundwater_list = groundwater_section.value[0:]
        for value in groundwater_list:
            if value.subcatchment == str(
                    self.tblGeneric.item(0, column).text()) and len(
                        value.custom_lateral_flow_equation) > 0:
                tb.textbox.setText('YES')
        tb.textbox.setEnabled(False)
        tb.column = column
        tb.button.clicked.connect(self.make_show_lateral(column))
        self.tblGeneric.setCellWidget(14, column, tb)

    def set_deep_equation(self, column):
        # text plus button for custom deep equation
        tb = TextPlusButton(self)
        tb.textbox.setText('NO')
        groundwater_section = self.project.groundwater
        groundwater_list = groundwater_section.value[0:]
        for value in groundwater_list:
            if value.subcatchment == str(
                    self.tblGeneric.item(0, column).text()) and len(
                        value.custom_deep_flow_equation) > 0:
                tb.textbox.setText('YES')
        tb.textbox.setEnabled(False)
        tb.column = column
        tb.button.clicked.connect(self.make_show_deep(column))
        self.tblGeneric.setCellWidget(15, column, tb)

    def make_show_lateral(self, column):
        def local_show():
            editor = frmGroundwaterEquation(
                self._main_form, str(self.tblGeneric.item(0, column).text()))
            editor.setWindowModality(QtCore.Qt.ApplicationModal)
            editor.show()
            self.refresh_column = column

        return local_show

    def make_show_deep(self, column):
        def local_show():
            editor = frmGroundwaterEquationDeep(
                self._main_form, str(self.tblGeneric.item(0, column).text()))
            editor.setWindowModality(QtCore.Qt.ApplicationModal)
            editor.show()
            self.refresh_column = column

        return local_show

    def cmdOK_Clicked(self):
        if self.new_item:
            self.project.groundwater.value.append(self.new_item)
        self.backend.new_item = None
        self.backend.apply_edits()
        self.close()

    def cmdCancel_Clicked(self):
        self.close()
class frmInfiltration(QtGui.QMainWindow, Ui_frmInfiltrationEditor):
    def __init__(self, parent, edit_these, new_item, title, **kwargs):
        QtGui.QMainWindow.__init__(self, parent)
        self.helper = HelpHandler(self)
        option_section = parent.project.find_section('OPTIONS')
        if option_section.infiltration=="HORTON" or option_section.infiltration=="MODIFIED_HORTON":
            self.help_topic = "swmm/src/src/hortoninfiltrationparameters.htm"
        elif option_section.infiltration=="GREEN_AMPT" or option_section.infiltration=="MODIFIED_GREEN_AMPT":
            self.help_topic = "swmm/src/src/green_amptinfiltrationparame.htm"
        elif option_section.infiltration=="CURVE_NUMBER":
            self.help_topic = "swmm/src/src/curvenumberinfiltrationpara.htm"
        self.setupUi(self)
        self.setWindowTitle(title)
        QtCore.QObject.connect(self.cmdOK, QtCore.SIGNAL("clicked()"), self.cmdOK_Clicked)
        QtCore.QObject.connect(self.cmdCancel, QtCore.SIGNAL("clicked()"), self.cmdCancel_Clicked)
        QtCore.QObject.connect(self.cboInfilModel, QtCore.SIGNAL("currentIndexChanged(int)"),
                               self.cboInfilModel_currentIndexChanged)

        self.defaults = None
        if kwargs.has_key("defaults"):
            self.defaults = kwargs["defaults"]
        enum_val = E_InfilModel.HORTON
        if self.defaults is not None:
            enum_val = E_InfilModel[self.defaults.properties_sub_values[self.defaults.infil_model_key]]
            # self.infil_model = self.qsettings.value(self.default_key, None)
            # if self.infil_model is None:
            #     self.infil_model = HortonInfiltration()
            #     self.infil_model.set_defaults()
            # else:
            #     enum_val = self.infil_model.model_type()
            #     if enum_val == E_InfilModel.HORTON or \
            #        enum_val == E_InfilModel.MODIFIED_HORTON:
            #         self.infil_model_horton.__dict__.update(self.infil_model.__dict__)
            #     elif enum_val == E_InfilModel.GREEN_AMPT or \
            #          enum_val == E_InfilModel.MODIFIED_GREEN_AMPT:
            #         self.infil_model_ga.__dict__.update(self.infil_model.__dict__)
            #     elif enum_val == E_InfilModel.CURVE_NUMBER:
            #         self.infil_model_cn.__dict__.update(self.infil_model.__dict__)

            self.cboInfilModel.setEnabled(True)
            if self.lblNotes:
                self.tblGeneric.currentCellChanged.connect(self.table_currentCellChanged)
            self.tblGeneric.itemChanged.connect(self.table_itemChanged)
            pass
        else:
            self.backend = PropertyEditorBackend(self.tblGeneric, self.lblNotes, parent, edit_these, new_item)
            #self.lblTop.setText("Infiltration Method:  " + parent.project.find_section('OPTIONS').infiltration)
            proj_infilmodel = parent.project.find_section('OPTIONS').infiltration
            enum_val = E_InfilModel[proj_infilmodel.upper()]
            self.cboInfilModel.setEnabled(False)

        set_combo_items(type(enum_val), self.cboInfilModel)
        set_combo(self.cboInfilModel, enum_val)

        self.corner_label = QtGui.QLabel("Property", self.tblGeneric)
        self.corner_label.setAlignment(QtCore.Qt.AlignCenter)
        self.corner_label.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)
        QtCore.QObject.connect(self.tblGeneric.verticalHeader(),
                               QtCore.SIGNAL("geometriesChanged()"), self.resizeCorner)
        QtCore.QObject.connect(self.tblGeneric.horizontalHeader(),
                               QtCore.SIGNAL("geometriesChanged()"), self.resizeCorner)

    def cboInfilModel_currentIndexChanged(self, currentIndex):
        #if self.infil_model is None: return
        if not self.defaults: return
        self.tblGeneric.clearContents()
        enum_val = E_InfilModel[self.cboInfilModel.currentText().upper()]
        if enum_val == E_InfilModel.HORTON or \
           enum_val == E_InfilModel.MODIFIED_HORTON:
            self.meta = self.defaults.infil_model_horton.metadata
            self.set_horton()
        elif enum_val == E_InfilModel.GREEN_AMPT or \
             enum_val == E_InfilModel.MODIFIED_GREEN_AMPT:
            self.meta = self.defaults.infil_model_ga.metadata
            self.set_greenampt()
        elif enum_val == E_InfilModel.CURVE_NUMBER:
            self.meta = self.defaults.infil_model_cn.metadata
            self.set_CN()

    def set_horton(self):
        #mtype = self.defaults.infil_model_horton.model_type()
        mtype = E_InfilModel[self.cboInfilModel.currentText().upper()]
        props = []
        for i in range(0, len(HortonInfiltration.metadata)):
            if "subcatch" in HortonInfiltration.metadata[i].label.lower():
                continue
            else:
                props.append(HortonInfiltration.metadata[i].label)
        self.tblGeneric.setRowCount(len(props))
        self.tblGeneric.setVerticalHeaderLabels(props)
        for i in range(0, self.tblGeneric.rowCount()):
            vtitle = self.tblGeneric.verticalHeaderItem(i).text().lower()
            if "max" in vtitle and "infil" in vtitle:
                val = self.defaults.infil_model_horton.default_max_rate()
                if mtype == E_InfilModel.MODIFIED_HORTON:
                    val = self.defaults.infil_model_horton.max_rate
                self.tblGeneric.setItem(i,0, QtGui.QTableWidgetItem(unicode(val)))
            elif "min" in vtitle and "infil" in vtitle:
                val = self.defaults.infil_model_horton.default_min_rate()
                if mtype == E_InfilModel.MODIFIED_HORTON:
                    val = self.defaults.infil_model_horton.min_rate
                self.tblGeneric.setItem(i,0, QtGui.QTableWidgetItem(unicode(val)))
            elif "decay" in vtitle:
                val = self.defaults.infil_model_horton.default_decay()
                if mtype == E_InfilModel.MODIFIED_HORTON:
                    val = self.defaults.infil_model_horton.decay
                self.tblGeneric.setItem(i,0, QtGui.QTableWidgetItem(unicode(val)))
            elif "dry" in vtitle:
                val = self.defaults.infil_model_horton.default_dry_time()
                if mtype == E_InfilModel.MODIFIED_HORTON:
                    val = self.defaults.infil_model_horton.dry_time
                self.tblGeneric.setItem(i,0, QtGui.QTableWidgetItem(unicode(val)))
            elif "max" in vtitle and "volume" in vtitle:
                val = self.defaults.infil_model_horton.default_max_volume()
                if mtype == E_InfilModel.MODIFIED_HORTON:
                    val = self.defaults.infil_model_horton.max_volume
                self.tblGeneric.setItem(i,0, QtGui.QTableWidgetItem(unicode(val)))

    def set_greenampt(self):
        #mtype = self.defaults.infil_model_ga.model_type()
        mtype = E_InfilModel[self.cboInfilModel.currentText().upper()]
        props = []
        for i in range(0, len(GreenAmptInfiltration.metadata)):
            if "subcatch" in GreenAmptInfiltration.metadata[i].label.lower():
                continue
            else:
                props.append(GreenAmptInfiltration.metadata[i].label)
        self.tblGeneric.setRowCount(len(props))
        self.tblGeneric.setVerticalHeaderLabels(props)
        #self.infil_model = GreenAmptInfiltration()
        for i in range(0, self.tblGeneric.rowCount()):
            vtitle = self.tblGeneric.verticalHeaderItem(i).text().lower()
            if "suction" in vtitle:
                val = self.defaults.infil_model_ga.default_suction()
                if mtype == E_InfilModel.MODIFIED_GREEN_AMPT:
                    val = self.defaults.infil_model_ga.suction
                self.tblGeneric.setItem(i,0, QtGui.QTableWidgetItem(unicode(val)))
            elif "conduct" in vtitle:
                val = self.defaults.infil_model_ga.default_conductivity()
                if mtype == E_InfilModel.MODIFIED_GREEN_AMPT:
                    val = self.defaults.infil_model_ga.hydraulic_conductivity
                self.tblGeneric.setItem(i,0, QtGui.QTableWidgetItem(unicode(val)))
            elif "deficit" in vtitle:
                val = self.defaults.infil_model_ga.default_init_deficit()
                if mtype == E_InfilModel.MODIFIED_GREEN_AMPT:
                    val = self.defaults.infil_model_ga.initial_moisture_deficit
                self.tblGeneric.setItem(i,0, QtGui.QTableWidgetItem(unicode(val)))

    def set_CN(self):
        props = []
        for i in range(0, len(CurveNumberInfiltration.metadata)):
            if "subcatch" in CurveNumberInfiltration.metadata[i].label.lower():
                continue
            elif "conduct" in CurveNumberInfiltration.metadata[i].label.lower():
                continue
            else:
                props.append(CurveNumberInfiltration.metadata[i].label)
        self.tblGeneric.setRowCount(len(props))
        self.tblGeneric.setVerticalHeaderLabels(props)
        #self.infil_model = CurveNumberInfiltration()
        for i in range(0, self.tblGeneric.rowCount()):
            vtitle = self.tblGeneric.verticalHeaderItem(i).text().lower()
            if "curve" in vtitle:
                val, val_is_good = ParseData.floatTryParse(self.defaults.infil_model_cn.curve_number)
                if val_is_good:
                    self.tblGeneric.setItem(i,0, QtGui.QTableWidgetItem(unicode(val)))
                else:
                    self.tblGeneric.setItem(i,0, QtGui.QTableWidgetItem(unicode(self.defaults.infil_model_cn.default_CN())))
            elif "dry" in vtitle:
                val, val_is_good = ParseData.floatTryParse(self.defaults.infil_model_cn.dry_days)
                if val_is_good:
                    self.tblGeneric.setItem(i,0, QtGui.QTableWidgetItem(unicode(val)))
                else:
                    self.tblGeneric.setItem(i,0, QtGui.QTableWidgetItem(unicode(self.defaults.infil_model_cn.default_dry_time())))

    def resizeCorner(self):
        self.corner_label.setGeometry(0, 0, self.tblGeneric.verticalHeader().width(),
                                           self.tblGeneric.horizontalHeader().height())

    def table_currentCellChanged(self):
        row = self.tblGeneric.currentRow()
        if self.lblNotes:
            if hasattr(self, "meta") and self.meta and self.meta[row]:
                self.lblNotes.setText(self.meta[row + 1].hint)
            else:
                self.lblNotes.setText('')

    def table_itemChanged(self, item):
        if self.tblGeneric.currentItem() is None: return
        new_val, new_val_is_good = ParseData.floatTryParse(self.tblGeneric.currentItem().text())
        if not new_val_is_good: return
        vtitle = self.tblGeneric.verticalHeaderItem(self.tblGeneric.currentRow()).text()

        attr_name = ""
        for i in range(0, len(self.meta)):
            if self.meta[i].label == vtitle:
                attr_name = self.meta[i].attribute
                break

        if len(attr_name) == 0: return

        enum_val = E_InfilModel[self.cboInfilModel.currentText().upper()]
        if enum_val == E_InfilModel.MODIFIED_HORTON:
            self.defaults.infil_model_horton.__dict__[attr_name] = new_val
        elif enum_val == E_InfilModel.MODIFIED_GREEN_AMPT:
            self.defaults.infil_model_ga.__dict__[attr_name] = new_val
        elif enum_val == E_InfilModel.CURVE_NUMBER:
            self.defaults.infil_model_cn.__dict__[attr_name] = new_val
        pass

    def cmdOK_Clicked(self):
        if hasattr(self, "backend") and self.backend is not None:
            self.backend.apply_edits()
        else:
            if self.defaults is not None:
                # self.qsettings.remove(self.default_key)
                enum_val = E_InfilModel[self.cboInfilModel.currentText().upper()]
                self.defaults.properties_sub_values[self.defaults.infil_model_key] = enum_val.name
                if enum_val == E_InfilModel.HORTON:
                    #self.qsettings.setValue(self.default_key, self.infil_model_horton)
                    self.defaults.infil_model_horton.set_defaults()
                elif enum_val == E_InfilModel.GREEN_AMPT:
                    #self.qsettings.setValue(self.default_key, self.infil_model_ga)
                    self.defaults.infil_model_ga.set_defaults()
        self.close()

    def cmdCancel_Clicked(self):
        self.close()
class frmGenericPropertyEditor(QMainWindow, Ui_frmGenericPropertyEditor):
    def __init__(self, session, project_section, edit_these, new_item, title):
        QMainWindow.__init__(self, session)
        self.setupUi(self)
        self.setWindowTitle(title)
        self.cmdOK.clicked.connect(self.cmdOK_Clicked)
        self.cmdCancel.clicked.connect(self.cmdCancel_Clicked)

        self.session = session
        self.project = session.project
        self.project_section = project_section
        if new_item:
            edit_these = [new_item]
        elif self.project_section and \
                isinstance(self.project_section.value, list) and \
                len(self.project_section.value) > 0 and \
                (not hasattr(self, "SECTION_TYPE") or isinstance(self.project_section.value[0], self.SECTION_TYPE)):

            if edit_these:  # Edit only specified item(s) in section
                if isinstance(edit_these[0], str):  # Translate list from names to objects
                    edit_names = edit_these
                    edit_objects = [item for item in self.project_section.value if item.name in edit_these]
                    edit_these = edit_objects

            else:  # Edit all items in section
                edit_these = []
                edit_these.extend(self.project_section.value)
        self.edit_these = edit_these
        self.backend = PropertyEditorBackend(self.tblGeneric, self.lblNotes, session, edit_these, new_item)
        self.tblGeneric.cellChanged.connect(self.check_change)
        for row in range(self.tblGeneric.rowCount()):
            self.tblGeneric.setRowHeight(row, 20)

        self._main_form = session
        if session.model == 'SWMM':
            if project_section.SECTION_NAME == '[LABELS]' or project_section.SECTION_NAME == '[POLLUTANTS]':
                word = project_section.SECTION_NAME.strip('[]')

                if (session.program_settings.value("Geometry/" + "frmGenericPropertyEditor_" + word + "_geometry") and
                        session.program_settings.value("Geometry/" + "frmGenericPropertyEditor_" + word + "_state")):
                    self.restoreGeometry(
                        session.program_settings.value("Geometry/" + "frmGenericPropertyEditor_" + word +
                                                       "_geometry", self.geometry(), type=QtCore.QByteArray))
                    self.restoreState(
                        session.program_settings.value("Geometry/" + "frmGenericPropertyEditor_" + word +
                                                       "_state", self.windowState(), type=QtCore.QByteArray))

    def header_index(self, prop):
        """
        Look up the row header to match up with prop
        Args:
            prop: header text
        Returns:
            row number of matching header text
        """
        header = ""
        for row in range(self.tblGeneric.rowCount()):
            header = self.tblGeneric.verticalHeaderItem(row).text()
            if header and prop.upper() in header.upper():
                return row
        return -999

    def is_name_duplicate(self, irow, icol):
        new_name = self.tblGeneric.item(irow, icol).text()
        existing_elem = None
        if self.project_section in self.project.nodes_groups():
            existing_elem = self.project.find_node(new_name)
        elif self.project_section in self.project.links_groups():
            existing_elem = self.project.find_link(new_name)
        else:
            existing_elem = self.project_section.find_item(new_name)
        if existing_elem is not None:
            return True
        else:
            return False

    def check_change(self, irow, icol):
        ori_value = getattr(self.backend.col_to_item_dict[icol], self.backend.meta[irow].attribute, '')
        new_value = self.tblGeneric.item(irow, icol).text()
        if not self.backend.loaded:
            return
        if irow == 0:
            if self.is_name_duplicate(irow, icol):
                elem_type = type(self.project_section.value[0]).__name__
                if self.project_section in self.project.nodes_groups():
                    elem_type = 'Node'
                elif self.project_section in self.project.links_groups():
                    elem_type = 'Link'
                QMessageBox.information(None, self.session.model,
                                        elem_type + " '" + new_value + "' already exists.",
                                        QMessageBox.Ok)
                self.tblGeneric.cellChanged.disconnect(self.check_change)
                self.tblGeneric.item(irow, icol).setText(ori_value)
                self.tblGeneric.cellChanged.connect(self.check_change)
        pass

    def cmdOK_Clicked(self):
        self.backend.apply_edits()
        # self.session.model_layers.create_layers_from_project(self.project)

        if self._main_form.model == 'SWMM':
            if self.project_section.SECTION_NAME == '[LABELS]' or self.project_section.SECTION_NAME == '[POLLUTANTS]':
                word = self.project_section.SECTION_NAME.strip('[]')
                self._main_form.program_settings.setValue("Geometry/" + "frmGenericPropertyEditor_" + word +
                                                          "_geometry", self.saveGeometry())
                self._main_form.program_settings.setValue("Geometry/" + "frmGenericPropertyEditor_" + word +
                                                          "_state", self.saveState())
        self.close()

    def cmdCancel_Clicked(self):
        self.close()

    def copy(self):
        selected_range = self.tblGeneric.selectedRanges()[0]
        str = ""
        for i in range(selected_range.rowCount()):
            if i > 0:
                str += "\n"
            for j in range(selected_range.columnCount()):
                if j > 0:
                    str += "\t"
                str += self.tblGeneric.item(selected_range.topRow() + i, selected_range.leftColumn() + j).text()
        str += "\n"
        QApplication.clipboard().setText(str)

    def paste(self):
        str = QApplication.clipboard().text()
        selected_range = self.tblGeneric.selectedRanges()[0]
        rows = str.split('\n')
        numRows = len(rows) - 1
        numColumns = rows[0].count('\t') + 1
        for i in range(numRows):
            columns = rows[i].split('\t')
            for j in range(numColumns):
                if selected_range.topRow() + i < self.tblGeneric.rowCount() and selected_range.leftColumn() + j < self.tblGeneric.columnCount():
                    self.tblGeneric.item(selected_range.topRow() + i, selected_range.leftColumn() + j).setText(columns[j])
        if selected_range.rowCount() > numRows or selected_range.columnCount() > numColumns:
            # not enough data to fill selected area, don't continue unless theres a single cell on the clipboard
            if numRows == 1 and numColumns == 1:
                # fill selected range with single value
                value = rows[0]
                for i in range(selected_range.rowCount()):
                    for j in range(selected_range.columnCount()):
                        self.tblGeneric.item(selected_range.topRow() + i, selected_range.leftColumn() + j).setText(value)
        pass

    def keyPressEvent(self, event):
        if event.matches(QtGui.QKeySequence.Copy):
            self.copy()
        if event.matches(QtGui.QKeySequence.Paste):
            self.paste()
class frmGroundwaterFlow(QtGui.QMainWindow, Ui_frmGroundwaterFlow):
    def __init__(self, main_form, edit_these, title):
        QtGui.QMainWindow.__init__(self, main_form)
        self.helper = HelpHandler(self)
        self.help_topic = "swmm/src/src/groundwaterfloweditordialog.htm"
        self._main_form = main_form
        self.project = main_form.project
        self.refresh_column = -1
        self.setupUi(self)
        self.setWindowTitle(title)
        QtCore.QObject.connect(self.cmdOK, QtCore.SIGNAL("clicked()"), self.cmdOK_Clicked)
        QtCore.QObject.connect(self.cmdCancel, QtCore.SIGNAL("clicked()"), self.cmdCancel_Clicked)
        self.backend = PropertyEditorBackend(self.tblGeneric, self.lblNotes, main_form, edit_these)

        for column in range(0, self.tblGeneric.columnCount()):
            # for aquifers, show available aquifers
            aquifer_section = main_form.project.find_section("AQUIFERS")
            aquifer_list = aquifer_section.value[0:]
            combobox = QtGui.QComboBox()
            combobox.addItem('')
            selected_index = 0
            for value in aquifer_list:
                combobox.addItem(value.name)
                if edit_these[column].aquifer == value.name:
                    selected_index = int(combobox.count())-1
            combobox.setCurrentIndex(selected_index)
            self.tblGeneric.setCellWidget(1, column, combobox)
            # also set special text plus button cells
            self.set_lateral_equation(column)
            self.set_deep_equation(column)

        self.installEventFilter(self)

    def eventFilter(self, ui_object, event):
        if event.type() == QtCore.QEvent.WindowUnblocked:
            if self.refresh_column > -1:
                self.set_lateral_equation(self.refresh_column)
                self.set_deep_equation(self.refresh_column)
                self.refresh_column = -1
        return False

    def set_lateral_equation(self, column):
        # text plus button for custom lateral equation
        tb = TextPlusButton(self)
        tb.textbox.setText('NO')
        groundwater_section = self.project.groundwater
        groundwater_list = groundwater_section.value[0:]
        for value in groundwater_list:
            if value.subcatchment == str(self.tblGeneric.item(0,column).text()) and len(value.custom_lateral_flow_equation) > 0:
                tb.textbox.setText('YES')
        tb.textbox.setEnabled(False)
        tb.column = column
        tb.button.clicked.connect(self.make_show_lateral(column))
        self.tblGeneric.setCellWidget(14, column, tb)

    def set_deep_equation(self, column):
        # text plus button for custom deep equation
        tb = TextPlusButton(self)
        tb.textbox.setText('NO')
        groundwater_section = self.project.groundwater
        groundwater_list = groundwater_section.value[0:]
        for value in groundwater_list:
            if value.subcatchment == str(self.tblGeneric.item(0,column).text()) and len(value.custom_deep_flow_equation) > 0:
                tb.textbox.setText('YES')
        tb.textbox.setEnabled(False)
        tb.column = column
        tb.button.clicked.connect(self.make_show_deep(column))
        self.tblGeneric.setCellWidget(15, column, tb)

    def make_show_lateral(self, column):
        def local_show():
            editor = frmGroundwaterEquation(self._main_form, str(self.tblGeneric.item(0, column).text()))
            editor.setWindowModality(QtCore.Qt.ApplicationModal)
            editor.show()
            self.refresh_column = column
        return local_show

    def make_show_deep(self, column):
        def local_show():
            editor = frmGroundwaterEquationDeep(self._main_form, str(self.tblGeneric.item(0, column).text()))
            editor.setWindowModality(QtCore.Qt.ApplicationModal)
            editor.show()
            self.refresh_column = column
        return local_show

    def cmdOK_Clicked(self):
        self.backend.apply_edits()
        self.close()

    def cmdCancel_Clicked(self):
        self.close()