class AdvancedVisualizationForm(QWidget):
    def __init__(self, mainwindow, result_manager):
        QWidget.__init__(self, mainwindow)
        #mainwindow is an OpusGui
        self.mainwindow = mainwindow
        self.result_manager = result_manager
        self.toolboxBase = self.result_manager.mainwindow.toolboxBase

        self.inGui = False
        self.logFileKey = 0

        self.xml_helper = ResultsManagerXMLHelper(toolboxBase=self.toolboxBase)
        self.result_generator = OpusResultGenerator(
            toolboxBase=self.toolboxBase)

        self.result_generator.guiElement = self

        self.tabIcon = QIcon(':/Images/Images/cog.png')
        self.tabLabel = 'Advanced Visualization'

        self.widgetLayout = QVBoxLayout(self)
        self.widgetLayout.setAlignment(Qt.AlignTop)

        self.resultsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.resultsGroupBox)

        self.dataGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.dataGroupBox)

        self.optionsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.optionsGroupBox)

        self._setup_definition_widget()

        self._setup_buttons()
        self._setup_tabs()

    def _setup_buttons(self):
        # Add Generate button...
        self.pbn_go = QPushButton(self.resultsGroupBox)
        self.pbn_go.setObjectName('pbn_go')
        self.pbn_go.setText(QString('Go!'))

        QObject.connect(self.pbn_go, SIGNAL('released()'),
                        self.on_pbn_go_released)
        self.widgetLayout.addWidget(self.pbn_go)

        self.pbn_set_esri_storage_location = QPushButton(self.optionsGroupBox)
        self.pbn_set_esri_storage_location.setObjectName(
            'pbn_set_esri_storage_location')
        self.pbn_set_esri_storage_location.setText(QString('...'))
        self.pbn_set_esri_storage_location.hide()

        QObject.connect(self.pbn_set_esri_storage_location,
                        SIGNAL('released()'),
                        self.on_pbn_set_esri_storage_location_released)

    def _setup_tabs(self):
        # Add a tab widget and layer in a tree view and log panel
        self.tabWidget = QTabWidget(self.resultsGroupBox)

        # Log panel
        self.logText = QTextEdit(self.resultsGroupBox)
        self.logText.setReadOnly(True)
        self.logText.setLineWidth(0)
        self.tabWidget.addTab(self.logText, 'Log')

        # Finally add the tab to the model page
        self.widgetLayout.addWidget(self.tabWidget)

#

    def _setup_definition_widget(self):

        #### setup results group box ####

        self.gridlayout = QGridLayout(self.resultsGroupBox)
        self.gridlayout.setObjectName('gridlayout')

        self.lbl_results = QLabel(self.resultsGroupBox)
        self.lbl_results.setObjectName('lbl_results')
        self.lbl_results.setText(QString('Results'))
        self.gridlayout.addWidget(self.lbl_results, 0, 0, 1, 3)

        self._setup_co_results()
        self.gridlayout.addWidget(self.co_results, 0, 3, 1, 10)

        self.pbn_add = QPushButton(self.resultsGroupBox)
        self.pbn_add.setObjectName('pbn_add')
        self.pbn_add.setText(QString('+'))

        QObject.connect(self.pbn_add, SIGNAL('released()'),
                        self.on_pbn_add_released)
        self.gridlayout.addWidget(self.pbn_add, 0, 14, 1, 1)

        self.lw_indicators = QListWidget(self.resultsGroupBox)
        self.lw_indicators.setObjectName('lw_indicators')
        self.gridlayout.addWidget(self.lw_indicators, 1, 1, 1, 13)

        self.pbn_remove = QPushButton(self.resultsGroupBox)
        self.pbn_remove.setObjectName('pbn_remove')
        self.pbn_remove.setText(QString('-'))

        QObject.connect(self.pbn_remove, SIGNAL('released()'),
                        self.on_pbn_remove_released)
        self.gridlayout.addWidget(self.pbn_remove, 1, 14, 1, 1)

        #### setup data group box ####

        self.gridlayout2 = QGridLayout(self.dataGroupBox)
        self.gridlayout2.setObjectName('gridlayout2')

        self._setup_co_result_style()
        self.gridlayout2.addWidget(self.co_result_style, 1, 0, 1, 2)

        self.lbl_result_style_sep = QLabel(self.resultsGroupBox)
        self.lbl_result_style_sep.setObjectName('lbl_result_style_sep')
        self.lbl_result_style_sep.setText(QString('<center>as</center>'))
        self.gridlayout2.addWidget(self.lbl_result_style_sep, 1, 2, 1, 1)

        self._setup_co_result_type()
        self.gridlayout2.addWidget(self.co_result_type, 1, 3, 1, 2)

        ##### setup options group box ####

        self.gridlayout3 = QGridLayout(self.optionsGroupBox)
        self.gridlayout3.setObjectName('gridlayout3')

        self.le_esri_storage_location = QLineEdit(self.optionsGroupBox)
        self.le_esri_storage_location.setObjectName('le_esri_storage_location')
        self.le_esri_storage_location.setText('[set path]')
        self.le_esri_storage_location.hide()
        self.optionsGroupBox.hide()

        QObject.connect(self.co_result_style,
                        SIGNAL('currentIndexChanged(int)'),
                        self.on_co_result_style_changed)
        QObject.connect(self.co_result_type,
                        SIGNAL('currentIndexChanged(int)'),
                        self.on_co_result_type_changed)

    def _setup_co_results(self):

        self.co_results = QComboBox(self.resultsGroupBox)
        self.co_results.setObjectName('co_results')
        self.co_results.addItem(QString('[select]'))

        results = self.xml_helper.get_available_results()

        for result in results:
            name = '%i.%s' % (result['run_id'], result['indicator_name'])
            self.co_results.addItem(QString(name))

    def _setup_co_result_style(self):
        available_styles = [
            'visualize',
            'export',
        ]
        self.co_result_style = QComboBox(self.dataGroupBox)
        self.co_result_style.setObjectName('co_result_style')

        for dataset in available_styles:
            self.co_result_style.addItem(QString(dataset))

    def _setup_co_result_type(self):
        available_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]

        self.co_result_type = QComboBox(self.dataGroupBox)
        self.co_result_type.setObjectName('co_result_type')

        for dataset in available_types:
            self.co_result_type.addItem(QString(dataset))

    def on_pbnRemoveModel_released(self):
        self.result_manager.removeTab(self)
        self.result_manager.updateGuiElements()

    def on_pbn_add_released(self):
        cur_selected = self.co_results.currentText()
        for i in range(self.lw_indicators.count()):
            if self.lw_indicators.item(i).text() == cur_selected:
                return

        self.lw_indicators.addItem(cur_selected)

    def on_pbn_remove_released(self):
        selected_idxs = self.lw_indicators.selectedIndexes()
        for idx in selected_idxs:
            self.lw_indicators.takeItem(idx.row())

    def on_co_result_style_changed(self, ind):
        available_viz_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]

        available_export_types = ['ESRI table (for loading in ArcGIS)']

        txt = self.co_result_style.currentText()
        if txt == 'visualize':
            available_types = available_viz_types
        else:
            available_types = available_export_types

        self.co_result_type.clear()
        for result_type in available_types:
            r_type = QString(result_type)
            self.co_result_type.addItem(r_type)

    def on_co_result_type_changed(self, ind):
        self.gridlayout3.removeWidget(self.le_esri_storage_location)
        self.gridlayout3.removeWidget(self.pbn_set_esri_storage_location)
        self.optionsGroupBox.hide()

        self.pbn_set_esri_storage_location.hide()
        self.le_esri_storage_location.hide()

        txt = self.co_result_type.currentText()

        print txt
        if txt == 'ESRI table (for loading in ArcGIS)':
            self.pbn_set_esri_storage_location.show()
            self.le_esri_storage_location.show()
            self.gridlayout3.addWidget(self.le_esri_storage_location, 0, 1, 1,
                                       6)
            self.gridlayout3.addWidget(self.pbn_set_esri_storage_location, 0,
                                       7, 1, 1)
            self.optionsGroupBox.show()

    def on_pbn_set_esri_storage_location_released(self):
        print 'pbn_set_esri_storage_location released'
        from opus_core.misc import directory_path_from_opus_path
        start_dir = directory_path_from_opus_path('opus_gui.projects')

        configDialog = QFileDialog()
        filter_str = QString("*.gdb")
        fd = configDialog.getExistingDirectory(
            self,
            QString("Please select an ESRI geodatabase (*.gdb)..."
                    ),  #, *.sde, *.mdb)..."),
            QString(start_dir),
            QFileDialog.ShowDirsOnly)
        if len(fd) != 0:
            fileName = QString(fd)
            fileNameInfo = QFileInfo(QString(fd))
            fileNameBaseName = fileNameInfo.completeBaseName()
            self.le_esri_storage_location.setText(fileName)

    def on_pbn_go_released(self):
        # Fire up a new thread and run the model
        print 'Go button pressed'

        # References to the GUI elements for status for this run...
        #self.statusLabel = self.runStatusLabel
        #self.statusLabel.setText(QString('Model initializing...'))

        indicator_names = []
        for i in range(self.lw_indicators.count()):
            indicator_names.append(str(self.lw_indicators.item(i).text()))

        if indicator_names == []:
            print 'no indicators selected'
            return

        indicator_type = str(self.co_result_type.currentText())
        indicator_type = {
            #'Map (per indicator per year)':'matplotlib_map',
            'Map (per indicator per year)': 'mapnik_map',
            'Chart (per indicator, spans years)': 'matplotlib_chart',
            'Table (per indicator, spans years)': 'table_per_attribute',
            'Table (per year, spans indicators)': 'table_per_year',
            'ESRI table (for loading in ArcGIS)': 'table_esri'
        }[indicator_type]

        kwargs = {}
        if indicator_type == 'table_esri':
            storage_location = str(self.le_esri_storage_location.text())
            if not os.path.exists(storage_location):
                print 'Warning: %s does not exist!!' % storage_location
            kwargs['storage_location'] = storage_location

        self.result_manager.addIndicatorForm(indicator_type=indicator_type,
                                             indicator_names=indicator_names,
                                             kwargs=kwargs)

    def runUpdateLog(self):
        self.logFileKey = self.result_generator._get_current_log(
            self.logFileKey)

    def runErrorFromThread(self, errorMessage):
        QMessageBox.warning(self.mainwindow, 'Warning', errorMessage)
class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.media = Phonon.MediaObject(self)
        ### video widget ####
        self.video = Phonon.VideoWidget(self)
        self.video.setMinimumSize(320,200)
        self.videoCuts = []
        self.myfilename = ""
        self.extension = ""
        self.t1 = ""
        self.t2 = ""
        self.t3 = ""
        self.t4 = ""
        self.t5 = ""
        self.t6 = ""

        ### open button ###
        self.button = QtGui.QPushButton('Choose Video', self)
        self.button.setFixedWidth(90)
        self.button.clicked.connect(self.handleButton)
        self.button.setStyleSheet(stylesheet(self))

		### context menu ####
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.popup2)

        ### play / pause button ###
        self.playbutton = QtGui.QPushButton('Play', self)
        self.playbutton.setFixedWidth(70)
        self.playbutton.clicked.connect(self.handlePlayButton)
        self.playbutton.setStyleSheet(stylesheet(self))
        self.connect(QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Space), self), QtCore.SIGNAL('activated()'), self.handlePlayButton)
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("Ctrl+o"), self), QtCore.SIGNAL('activated()'), self.handleButton)
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("Ctrl+s"), self), QtCore.SIGNAL('activated()'), self.handleSaveVideo)
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("Ctrl+q"), self), QtCore.SIGNAL('activated()'), self.handleQuit)
        ### save button ###
        self.savebutton = QtGui.QPushButton('Save Video', self)
        self.savebutton.setFixedWidth(90)
        self.savebutton.clicked.connect(self.handleSaveVideo)
        self.savebutton.setStyleSheet(stylesheet(self))

        ### seek slider ###
        self.slider = Phonon.SeekSlider(self.media)
        self.slider.setStyleSheet(stylesheet(self))
        isize = QSize(16,16)
        self.slider.setIconSize(isize)
        self.slider.setFocus()
       # self.slider.connect(self.handleLabel)

        ### connection position to label ###
        self.media.isSeekable()
        self.media.tick.connect(self.handleLabel)
        self.media.seekableChanged.connect(self.handleLabel)
        #self.slider.wheel.connect(self.handleLabel)

        ### table view ###
        self.iconList = QListWidget()
        self.iconList.setAlternatingRowColors(True)
        self.iconList.setFixedWidth(200)
        self.iconList.setContextMenuPolicy(Qt.CustomContextMenu)
        self.iconList.setStyleSheet("QListWidget::item:selected:active { background: #7D8ED9; color:#FFFFFF; } ")
        self.iconList.setViewMode(0)
        self.iconList.setSelectionBehavior(1)
        self.iconList.setIconSize(QSize(80, 80/1.78))
        self._hookListActions()
        self.iconList.customContextMenuRequested.connect(self._openListMenu)

                ### set start button ###
        self.startbutton = QtGui.QPushButton('set Start', self)
        self.startbutton.setFixedWidth(70)
        self.startbutton.clicked.connect(self.handleStartButton)
        self.startbutton.setStyleSheet(stylesheet(self))
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("s"), self), QtCore.SIGNAL('activated()'), self.handleStartButton)

                ### set end button ###
        self.endbutton = QtGui.QPushButton('set End', self)
        self.endbutton.setFixedWidth(70)
        self.endbutton.clicked.connect(self.handleEndButton)
        self.endbutton.setStyleSheet(stylesheet(self))
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("e"), self), QtCore.SIGNAL('activated()'), self.handleEndButton)
                ### label ###
        self.mlabel = QtGui.QLabel('Frame', self)
        self.mlabel.setStyleSheet('QLabel \
				{background-color: transparent; color: white;}\nQLabel{color: darkcyan; font-size: 12px; background-color: transparent; border-radius: 5px; padding: 6px; text-align: center;}\n QLabel:hover{color: red;}')
        #self.mlabel.setFixedWidth(80)

        ### layout ###
        layout = QtGui.QGridLayout(self)
        layout.addWidget(self.iconList, 0, 0, 1, 1)
        layout.addWidget(self.video, 0, 1, 1, 6)
        layout.addWidget(self.slider, 1, 1, 1, 6)
        layout.addWidget(self.button, 2, 0, 1, 1)
        layout.addWidget(self.savebutton, 2, 1, 1, 1)
        layout.addWidget(self.playbutton, 2, 3, 1, 1)
        layout.addWidget(self.startbutton, 2, 5, 1, 1)
        layout.addWidget(self.endbutton, 2, 6, 1, 1)
        layout.addWidget(self.mlabel, 2, 4, 1, 1)

    def popup2(self, pos):	
        contextmenu = QMenu()
        contextmenu.addAction("Play / Pause (SPACE)", self.handlePlayButton)
        contextmenu.addSeparator()
        contextmenu.addAction("Load Video (Ctrl-O)", self.handleButton)
        contextmenu.addAction("Save Video (Ctrl-S)", self.handleSaveVideo)
        contextmenu.addSeparator()
        contextmenu.addAction("Info", self.handleInfo)
        contextmenu.addSeparator()
        contextmenu.addAction("Exit (q)", self.handleQuit)
        contextmenu.exec_(QCursor.pos())

    def handleInfo(self):
            msg = QMessageBox()
            #msg.setFixedSize(500, 300)
            #msg.setGeometry(100,100, 400, 200)
            msg.setIcon(QMessageBox.Information)
            msg.setText("Axel Schneider")
            msg.setInformativeText(unicode(u"©2016"))
            msg.setWindowTitle("Cut Video")
            msg.setDetailedText("Python Qt4")
            msg.setStandardButtons(QMessageBox.Ok)
	
            retval = msg.exec_()
            print "value of pressed message box button:", retval

    def handleQuit(self):
        app.quit()

    def handleButton(self):
        if self.media.state() == Phonon.PlayingState:
            self.media.stop()
        else:
            path = QtGui.QFileDialog.getOpenFileName(self, ("Video laden"),
                                                	'/Axel_1/Filme',
                                                	"Videos (*.ts *.mp4)")
            if path:
                self.myfilename = unicode(path) #.encode("utf-8")
                window.setWindowTitle(self.myfilename.split("/")[-1])
                self.extension = path.split(".")[1]
                print(self.extension)
                self.media.setCurrentSource(Phonon.MediaSource(path))
                self.video.setScaleMode(1)
                self.video.setAspectRatio(1)
                self.audio = Phonon.AudioOutput(Phonon.VideoCategory, self)
                Phonon.createPath(self.media, self.audio)
                Phonon.createPath(self.media, self.video)
                self.media.play()
                self.playbutton.setText('Pause')

    def handleSaveVideo(self):
        result = QFileDialog.getSaveFileName(self, ("Video speichern"),
             						'/tmp/film.' + str(self.extension),
             						"Videos (*.ts *.mp4)")
        if result:
            target = unicode(result)
            self.t1 = float(self.videoCuts[0])
            self.t2 = float(self.videoCuts[1])
            ffmpeg_extract_subclip(self.myfilename, self.t1, self.t2, targetname=target)
            window.setWindowTitle("Film gespeichert")
            self.purgeMarker()

    def handlePlayButton(self):
        if self.media.state() == Phonon.PlayingState:
            self.media.pause()
            self.playbutton.setText('Play')
				
        else:
            #print(self.iconList.count())
            self.media.play()
            self.playbutton.setText('Pause')

    def handleStartButton(self):
        if self.iconList.count() < 2:
            rm = str(self.media.currentTime() / 100.00 / 10.00)
            item = QListWidgetItem()
            img = QImage(self.video.snapshot())
            pix = QtGui.QPixmap.fromImage(img)
            item.setIcon(QIcon(pix))
            item.setText("Start: " + rm)
            self.iconList.addItem(item)
            self.videoCuts.append(rm)
        else:
            return

    def handleEndButton(self):
        if self.iconList.count() < 2:
            rm = str(self.media.currentTime() / 100.00 / 10.00)
            item = QListWidgetItem()
            #item.setSizeHint(QSize(150, 40))
            img = QImage(self.video.snapshot())
            pix = QtGui.QPixmap.fromImage(img)
            item.setIcon(QIcon(pix))
            item.setText("End: " + rm)
            self.iconList.addItem(item)
            self.videoCuts.append(rm)
            self.t3 = float(str(self.media.remainingTime()))
            print(self.t3)
            self.media.stop()
            self.playbutton.setText('Play')
        else:
            return

    def handleLabel(self):
            ms = self.media.currentTime()
            seconds=str((ms/1000)%60)
            minutes=str((ms/(1000*60))%60)
            hours=str((ms/(1000*60*60))%24)
            if int(seconds) < 10:
                seconds = "0" + seconds
            if int(minutes) < 10:
                minutes = "0" + minutes
            if int(hours) < 10:
                hours = "0" + hours
                s = hours + ":" + minutes + ":" + seconds
                self.mlabel.setText(s)

    def _hookListActions(self):
        #TOO bad-the list model -should be here...
        rmAction = QtGui.QAction(QtGui.QIcon('icons/close-x.png'), 'entfernen', self)
        rmAction.triggered.connect(self._removeMarker)
        rmAllAction = QtGui.QAction(QtGui.QIcon('icons/clear-all.png'), 'alle entfernen', self)
        rmAllAction.triggered.connect(self.purgeMarker)
        self.gotoAction = QtGui.QAction(QtGui.QIcon('icons/go-next.png'), 'zu dieser Position springen', self)
        self.gotoAction.triggered.connect(self._gotoFromMarker)

        #menus
        self._listMenu = QMenu()
        self._listMenu.addAction(self.gotoAction)
        self._listMenu.addSeparator()
        self._listMenu.addAction(rmAction)
        self._listMenu.addAction(rmAllAction)

    #---List widget context menu
    def _removeMarker(self,whatis):
        selectionList = self.iconList.selectedIndexes()
        if len(selectionList)==0:
            return
        item = selectionList[0]
        self.iconList.takeItem(item.row())
        #self.videoCuts.remove[1])

    def clearMarkerList(self):
        self.iconList.clear()

    #remove contents, remove file
    def purgeMarker(self):
        self.iconList.clear()
        self.videoCuts = []

    def _gotoFromMarker(self,whatis):
        selectionList = self.iconList.selectedIndexes()
        if len(selectionList)==0:
            return
        item = selectionList[0]
        pos = item.data().toString().replace("Start: ", "").replace("End: ", "")
        #frame = pos.ToInt()
        #self.video.currentTime = 1589
        self.setWindowTitle(pos)

    def _openListMenu(self,position):
        selectionList = self.iconList.selectedIndexes()
        if len(selectionList)==0:
            return
        self._listMenu.exec_(self.iconList.viewport().mapToGlobal(position))
class AdvancedVisualizationForm(QWidget):
    def __init__(self, mainwindow, result_manager):
        QWidget.__init__(self, mainwindow)
        #mainwindow is an OpusGui
        self.mainwindow = mainwindow
        self.result_manager = result_manager
        self.toolboxBase = self.result_manager.mainwindow.toolboxBase

        self.inGui = False
        self.logFileKey = 0
        
        self.xml_helper = ResultsManagerXMLHelper(toolboxBase = self.toolboxBase)
        self.result_generator = OpusResultGenerator(
                                    toolboxBase = self.toolboxBase)
            
        self.result_generator.guiElement = self
        
        self.tabIcon = QIcon(':/Images/Images/cog.png')
        self.tabLabel = 'Advanced Visualization'

        self.widgetLayout = QVBoxLayout(self)
        self.widgetLayout.setAlignment(Qt.AlignTop)

        self.resultsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.resultsGroupBox)
        
        self.dataGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.dataGroupBox)
        
        self.optionsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.optionsGroupBox)
                
        self._setup_definition_widget()

        self._setup_buttons()
        self._setup_tabs()
        
    def _setup_buttons(self):
        # Add Generate button...
        self.pbn_go = QPushButton(self.resultsGroupBox)
        self.pbn_go.setObjectName('pbn_go')
        self.pbn_go.setText(QString('Go!'))
        
        QObject.connect(self.pbn_go, SIGNAL('released()'),
                        self.on_pbn_go_released)
        self.widgetLayout.addWidget(self.pbn_go)
        
        self.pbn_set_esri_storage_location = QPushButton(self.optionsGroupBox)
        self.pbn_set_esri_storage_location.setObjectName('pbn_set_esri_storage_location')
        self.pbn_set_esri_storage_location.setText(QString('...'))
        self.pbn_set_esri_storage_location.hide()
        
        QObject.connect(self.pbn_set_esri_storage_location, SIGNAL('released()'),
                        self.on_pbn_set_esri_storage_location_released)
        
    def _setup_tabs(self):
        # Add a tab widget and layer in a tree view and log panel
        self.tabWidget = QTabWidget(self.resultsGroupBox)
    
        # Log panel
        self.logText = QTextEdit(self.resultsGroupBox)
        self.logText.setReadOnly(True)
        self.logText.setLineWidth(0)
        self.tabWidget.addTab(self.logText,'Log')

        # Finally add the tab to the model page
        self.widgetLayout.addWidget(self.tabWidget)
        
#
    def _setup_definition_widget(self):
        
        #### setup results group box ####
        
        self.gridlayout = QGridLayout(self.resultsGroupBox)
        self.gridlayout.setObjectName('gridlayout')

        self.lbl_results = QLabel(self.resultsGroupBox)
        self.lbl_results.setObjectName('lbl_results')
        self.lbl_results.setText(QString('Results'))
        self.gridlayout.addWidget(self.lbl_results,0,0,1,3)

        self._setup_co_results()
        self.gridlayout.addWidget(self.co_results,0,3,1,10)

        self.pbn_add = QPushButton(self.resultsGroupBox)
        self.pbn_add.setObjectName('pbn_add')
        self.pbn_add.setText(QString('+'))
        
        QObject.connect(self.pbn_add, SIGNAL('released()'),
                        self.on_pbn_add_released)
        self.gridlayout.addWidget(self.pbn_add, 0, 14, 1, 1)

        self.lw_indicators = QListWidget(self.resultsGroupBox)
        self.lw_indicators.setObjectName('lw_indicators')
        self.gridlayout.addWidget(self.lw_indicators,1,1,1,13)

        self.pbn_remove = QPushButton(self.resultsGroupBox)
        self.pbn_remove.setObjectName('pbn_remove')
        self.pbn_remove.setText(QString('-'))
        
        QObject.connect(self.pbn_remove, SIGNAL('released()'),
                        self.on_pbn_remove_released)
        self.gridlayout.addWidget(self.pbn_remove, 1, 14, 1, 1)


        #### setup data group box ####

        self.gridlayout2 = QGridLayout(self.dataGroupBox)
        self.gridlayout2.setObjectName('gridlayout2')

        self._setup_co_result_style()
        self.gridlayout2.addWidget(self.co_result_style,1,0,1,2)
                
        self.lbl_result_style_sep = QLabel(self.resultsGroupBox)
        self.lbl_result_style_sep.setObjectName('lbl_result_style_sep')
        self.lbl_result_style_sep.setText(QString('<center>as</center>'))
        self.gridlayout2.addWidget(self.lbl_result_style_sep,1,2,1,1)

        self._setup_co_result_type()
        self.gridlayout2.addWidget(self.co_result_type,1,3,1,2)

        ##### setup options group box ####
        
        self.gridlayout3 = QGridLayout(self.optionsGroupBox)
        self.gridlayout3.setObjectName('gridlayout3')
        
        self.le_esri_storage_location = QLineEdit(self.optionsGroupBox)
        self.le_esri_storage_location.setObjectName('le_esri_storage_location')
        self.le_esri_storage_location.setText('[set path]')
        self.le_esri_storage_location.hide()
        self.optionsGroupBox.hide()

        
        QObject.connect(self.co_result_style, SIGNAL('currentIndexChanged(int)'),
                self.on_co_result_style_changed)
        QObject.connect(self.co_result_type, SIGNAL('currentIndexChanged(int)'),
                self.on_co_result_type_changed)

    def _setup_co_results(self):
        
        self.co_results = QComboBox(self.resultsGroupBox)
        self.co_results.setObjectName('co_results')
        self.co_results.addItem(QString('[select]'))
        
        results = self.xml_helper.get_available_results()
            
        for result in results:
            name = '%i.%s'%(result['run_id'],result['indicator_name'])
            self.co_results.addItem(QString(name))

    def _setup_co_result_style(self):
        available_styles = [
            'visualize',
            'export',
        ]
        self.co_result_style = QComboBox(self.dataGroupBox)
        self.co_result_style.setObjectName('co_result_style')
        
        for dataset in available_styles:
            self.co_result_style.addItem(QString(dataset))

    def _setup_co_result_type(self):
        available_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]
                
        self.co_result_type = QComboBox(self.dataGroupBox)
        self.co_result_type.setObjectName('co_result_type')
        
        for dataset in available_types:
            self.co_result_type.addItem(QString(dataset))
                    
    def on_pbnRemoveModel_released(self):
        self.result_manager.removeTab(self)
        self.result_manager.updateGuiElements()
        
    def on_pbn_add_released(self):
        cur_selected = self.co_results.currentText()        
        for i in range(self.lw_indicators.count()):
            if self.lw_indicators.item(i).text() == cur_selected:
                return
        
        self.lw_indicators.addItem(cur_selected)
        
    def on_pbn_remove_released(self):
        selected_idxs = self.lw_indicators.selectedIndexes()
        for idx in selected_idxs:
            self.lw_indicators.takeItem(idx.row())
        
    def on_co_result_style_changed(self, ind):
        available_viz_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]
        
        available_export_types = [
            'ESRI table (for loading in ArcGIS)'
        ]
                
        txt = self.co_result_style.currentText()
        if txt == 'visualize':
            available_types = available_viz_types
        else:
            available_types = available_export_types
            
        self.co_result_type.clear()
        for result_type in available_types:
            r_type = QString(result_type)
            self.co_result_type.addItem(r_type)
    
    def on_co_result_type_changed(self, ind):
        self.gridlayout3.removeWidget(self.le_esri_storage_location)
        self.gridlayout3.removeWidget(self.pbn_set_esri_storage_location)
        self.optionsGroupBox.hide()
        
        self.pbn_set_esri_storage_location.hide()
        self.le_esri_storage_location.hide()
        
        txt = self.co_result_type.currentText()

        print txt
        if txt == 'ESRI table (for loading in ArcGIS)':
            self.pbn_set_esri_storage_location.show()   
            self.le_esri_storage_location.show()   
            self.gridlayout3.addWidget(self.le_esri_storage_location,0,1,1,6)
            self.gridlayout3.addWidget(self.pbn_set_esri_storage_location,0,7,1,1)   
            self.optionsGroupBox.show()   
            
    def on_pbn_set_esri_storage_location_released(self):
        print 'pbn_set_esri_storage_location released'
        from opus_core.misc import directory_path_from_opus_path
        start_dir = directory_path_from_opus_path('opus_gui.projects')

        configDialog = QFileDialog()
        filter_str = QString("*.gdb")
        fd = configDialog.getExistingDirectory(self,QString("Please select an ESRI geodatabase (*.gdb)..."), #, *.sde, *.mdb)..."),
                                          QString(start_dir), QFileDialog.ShowDirsOnly)
        if len(fd) != 0:
            fileName = QString(fd)
            fileNameInfo = QFileInfo(QString(fd))
            fileNameBaseName = fileNameInfo.completeBaseName()
            self.le_esri_storage_location.setText(fileName)
            
                
    def on_pbn_go_released(self):
        # Fire up a new thread and run the model
        print 'Go button pressed'

        # References to the GUI elements for status for this run...
        #self.statusLabel = self.runStatusLabel
        #self.statusLabel.setText(QString('Model initializing...'))
        
        indicator_names = []
        for i in range(self.lw_indicators.count()):
            indicator_names.append(str(self.lw_indicators.item(i).text()))
                
        if indicator_names == []:
            print 'no indicators selected'
            return
                
        indicator_type = str(self.co_result_type.currentText())
        indicator_type = {
            #'Map (per indicator per year)':'matplotlib_map',
            'Map (per indicator per year)':'mapnik_map',
            'Chart (per indicator, spans years)':'matplotlib_chart',
            'Table (per indicator, spans years)':'table_per_attribute',
            'Table (per year, spans indicators)':'table_per_year',
            'ESRI table (for loading in ArcGIS)':'table_esri'
        }[indicator_type]
        
        kwargs = {}
        if indicator_type == 'table_esri':
            storage_location = str(self.le_esri_storage_location.text())
            if not os.path.exists(storage_location):
                print 'Warning: %s does not exist!!'%storage_location
            kwargs['storage_location'] = storage_location
        
        self.result_manager.addIndicatorForm(indicator_type = indicator_type,
                                             indicator_names = indicator_names,
                                             kwargs = kwargs)

    def runUpdateLog(self):
        self.logFileKey = self.result_generator._get_current_log(self.logFileKey)


    def runErrorFromThread(self,errorMessage):
        QMessageBox.warning(self.mainwindow, 'Warning', errorMessage)