################################################################################
# ImageViewer widgets/toolbar implementation
################################################################################
from PyQt4 import QtCore, QtGui, QAxContainer
from core.modules.vistrails_module import Module
from packages.spreadsheet.basic_widgets import SpreadsheetCell, CellLocation
from packages.spreadsheet.spreadsheet_cell import QCellWidget, QCellToolBar
from packages.spreadsheet.spreadsheet_controller import spreadsheetController
from SahmViewerCell import Ui_Frame
#import imageviewer_rc
import os
################################################################################

class SAHMModelOutputViewerCell(SpreadsheetCell):
    """
    SAHMModelOutputViewerCell displays the various non-spatial
    outputs from a SAHM Model run
    """
    _input_ports = [("row", "(edu.utah.sci.vistrails.basic:Integer)"),
                    ("column", "(edu.utah.sci.vistrails.basic:Integer)"),
                    ('ModelWorkspace', '(edu.utah.sci.vistrails.basic:File)')]
     
    def compute(self):
        """ compute() -> None
        Dispatch the display event to the spreadsheet with images and labels
        
        """
        if self.has_input("ModelWorkspace"):
            window = spreadsheetController.findSpreadsheetWindow()
            model_workspace = self.get_input("ModelWorkspace").name
            model_dir_full = os.path.normcase(os.path.split(model_workspace)[0])
            model_dir = os.path.split(model_dir_full)[1]
            model_name = model_dir[:model_dir.index('output')]
            
#            prob_map_path = os.path.join(model_dir_full, model_name + '_prob_map.jpeg')
#            prob_map = window.file_pool.make_local_copy(prob_map_path)
            
            auc_graph_path = os.path.join(model_dir_full, model_name + '_auc_plot.jpg')
            auc_graph = window.file_pool.make_local_copy(auc_graph_path)
            
            text_output_path = os.path.join(model_dir_full, model_name + '_output.txt')
            text_output = window.file_pool.make_local_copy(text_output_path)
            
            response_path = os.path.join(model_dir_full, model_name + '_response_curves.pdf')
            response_curves = window.file_pool.make_local_copy(response_path)
            
            model_label = model_dir.capitalize().replace('output', 'Output')
            
            
            if self.has_input("row"):
                if not self.location:
                    self.loc
ation = CellLocation()
                self.location.row = self.get_input('row') - 1
            
            if self.has_input("column"):
                if not self.location:
                    self.location = CellLocation()
                self.location.col = self.get_input('column') - 1
            
        else:
            fileValue = None
        self.cellWidget = self.displayAndWait(SAHMOutputViewerCellWidget, (auc_graph, 
                                               
                       text_output,
                                                                      response_curves,
                                                                      model_label))

class SAHMOutputViewerCellWidget(QCellWidget):
    """
    SAHMOutputViewerCellWidget is the widget that will display the various
    non spatial outputs from a model run
    """
    def __init__(self, parent=None):
        QCellWidget.__init__(self, parent)
        
        centralLayout = QtGui.QVBoxLayout()
        self.setLayout(centralLayout)
        centralLayout.setMargin(0)
        centralLayout.setSpacing(0)

        
#        self.setAnimationEnabled(True)
        
        self.Frame = QtGui.QFrame()
        self.ui = Ui_Frame()
        self.ui.setupUi(self.Frame)
        
#        #add scenes to our graphicViews
#        self.gs_prob_map = QtGui.QGraphicsScene()
#        self.ui.gv_prob_map.setScene(self.gs_prob_map)
#        self.gs_prob_map.wheelEvent = self.wheel_event_prob
        
        self.gs_auc_graph = QtGui.QGraphicsScene()
        self.ui.gv_auc.setScene(self.gs_auc_graph)
        self.gs_auc_graph.wheelEvent = self.wheel_event_auc
        
        #add in ie browsers for the text and response
        self.text_browser = QAxContainer.QAxWidget(self)
        self.text_browser.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.text_browser.setControl("{8856F961-340A-11D0-A96B-00C04FD705A2}")
        self.ui.text_output_layout.addWidget(self.text_browser)
        self.text_urlSrc = None
        
        self.response_browser = QAxContainer.QAxWidget(self)
        self.response_browser.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.response_browser.setControl("{8856F961-340A-11D0-A96B-00C04FD705A2}")
        self.ui.response_curves_layout.addWidget(self.response_browser)
        self.response_urlSrc = None
        
        
        self.layout().addWidget(self.Frame)

    def updateContents(self, inputPorts):
        """ updateContents(inputPorts: tuple) -> None
        Update the widget contents based on the input data
        
        """
        (auc_graph, text_output, response_curves, model_label) = inputPorts
        
        self.images = {}
#        if prob_map:
#            #Value = (full image, sized image, scene, view, max_height)
#            pixmap = QtGui.QPixmap(prob_map.name)
#            max_size = self.getMaxSize(self.ui.gv_prob_map)
#            scaled_pixmap = pixmap.scaled(max_size, max_size, 
#                                            QtCore.Qt.KeepAspectRatio, 
#                                            QtCore.Qt.FastTransformation)
#            
#            self.images['prob_map'] = [pixmap,
#                                       scaled_pixmap,
#                                       self.gs_prob_map,
#                                       self.ui.gv_prob_map,
#                                       max_size]
        
        if auc_graph:
            pixmap = QtGui.QPixmap(auc_graph.name)
            max_size = self.getMaxSize(self.ui.gv_auc)
            scaled_pixmap = pixmap.scaled(max_size, max_size, 
                                            QtCore.Qt.KeepAspectRatio, 
                                            QtCore.Qt.SmoothTransformation)
            
            self.images['auc_graph'] = [pixmap,
                                       scaled_pixmap,
                                       self.gs_auc_graph,
                                       self.ui.gv_auc,
                                       max_size]
        
        

        self.text_urlSrc = QtCore.QUrl.fromLocalFile(text_output.name)
        if self.text_urlSrc!=None:
            self.text_browser.dynamicCall('Navigate(const QString&)', self.text_urlSrc.toString())
        else:
            self.text_browser.dynamicCall('Navigate(const QString&)', QtCore.QString('about:blank'))

        self.response_urlSrc = QtCore.QUrl.fromLocalFile(response_curves.name)
        if self.response_urlSrc!=None:
            self.response_browser.dynamicCall('Navigate(const QString&)', self.response_urlSrc.toString())
        else:
            self.response_browser.dynamicCall('Navigate(const QString&)', QtCore.QString('about:blank'))

        self.view_current()

        #QCellWidget.updateContents(self, inputPorts)

    def getMaxSize(self, view):
        return self.Frame.size().width() - 10
#        if view.size().width()  <= view.size().height(): 
#            return view.size().width() * 0.95
#        else: 
#            return view.size().height() * 0.95
    
    def view_current(self):
        for k,v in self.images.iteritems():
            size_img = v[1].size() 
            wth, hgt = QtCore.QSize.width(size_img), QtCore.QSize.height(size_img) 
            v[2].clear() 
            v[2].setSceneRect(0, 0, wth, hgt) 
            v[2].addPixmap(v[1]) 
        QtCore.QCoreApplication.processEvents() 

    def wheel_event_prob(self, event):
        self.wheel_event(event, 'prob_map', QtCore.Qt.FastTransformation)

    def wheel_event_auc(self, event):
        self.wheel_event(event, 'auc_graph', QtCore.Qt.SmoothTransformation)

    def whe