"""
     CCP4WebPluginFactory.py: CCP4 GUI Project
     Copyright (C) 2010 University of York

     This library is free software: you can redistribute it and/or
     modify it under the terms of the GNU Lesser General Public License
     version 3, modified in accordance with the provisions of the 
     license to address the requirements of UK law.
 
     You should have received a copy of the modified GNU Lesser General 
     Public License along with this library.  If not, copies may be 
     downloaded from http://www.ccp4.ac.uk/ccp4license.php
 
     This program is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU Lesser General Public License for more details.
"""

"""
     Liz Potterton Jan 2010 - Simple demo CCP4WebPluginFactory and a test plugin
"""

import sys,os, functools
from PyQt4 import QtWebKit, QtGui, QtCore
from CCP4ErrorHandling import *
from CCP4Config import DEVELOPER
import CCP4ReportWidgets


##@package CCP4WebPluginFactory  (QtWebKit) Demo of webkit plgin widgets
# A trivial button to test PyQt/Javascript interface

class ccp4_test_plugin(QtGui.QWidget):
   def __init__(self,text='',parent=None,argumentNames=[],argumentValues=[]):
     QtGui.QWidget. __init__(self,parent)
     #for ii in range(len(argumentNames)): print 'ccp4_test_plugin',argumentNames[ii],argumentValues[ii]
     layout = QtGui.QGridLayout()
     self.label = QtGui.QLabel(text,self)
     self.label.setMinimumWidth(300)
     layout.addWidget(self.label,0,0)
     self.image = QtGui.QLabel(self)
     pixmap = QtGui.QPixmap(os.path.join(os.environ['CCP4I2'],'test','data','ramachandran.png')).scaled(200,200)
     self.image.setPixmap(pixmap)
     layout.addWidget(self.image,1,1)
     self.setLayout(layout)
     #self.connect(self.image,QtCore.SIGNAL('clicked()'),self.handleImageClick)

   def handleImageClick(self):
     #print 'handleImageClick'
     pass

   @QtCore.pyqtSlot()
   def changeColour(self):
     #print 'changeColour'
     palette = QtGui.QPalette()
     palette.setColor(QtGui.QPalette.Normal,QtGui.QPalette.Window,QtGui.QColor(QtCore.Qt.cyan))
     self.setPalette(palette)
     
   @QtCore.pyqtSlot()
   def clearText(self):
     #print 'clearText'    
     self.label.setText('')

   @QtCore.pyqtSlot(unicode)
   def setLabelText(self, s):
     #print 'setLabelText',s
     self.label.setText(s)
     
   @QtCore.pyqtSlot(result=unicode)
   def value(self):
     #print 'value',self.label.text()
     return self.label.text()

   @QtCore.pyqtSlot()
   def update(self):
      # This is bad - assumes existance of another specific element on the html page
      # But does demo that can access html page
      frame = self.parent().page().mainFrame()
      qv = frame.evaluateJavaScript("test_text_input.value")
      #print 'ccp4_test_plugin.update qv',qv,qv.type(),qv.toString()
      self.label.setText(qv.toString())
      #text_input = self.parent().page().mainFrame().findAllElements("test_text_input") - qt4.6
      #print "text_input",text_input.evaluateJavaScript("this.value").toString()
      #self.setText(text_input.evaluateJavaScript("this.value").toString())


# The WebPluginFactory.
# QWebKit will only allow one WebPluginFactory per page so this one class must provide all
# CCP4 plugins. So there needs to be a mechanism to add plugins to this plugin factory!

class CWebPluginFactory(QtWebKit.QWebPluginFactory):

   ERROR_CODES= { 101 : { 'description' : 'Unknown error creating a widget' }
                  }

   def __init__(self,parent=None):
     QtWebKit.QWebPluginFactory.__init__(self,parent)
     #print 'CWebPluginFactory.init',parent,getattr(parent,'report')
     import CCP4Utils
     import inspect
     self.reportWidgets = {}
     module,err = CCP4Utils.importFileModule(os.path.join(CCP4Utils.getCCP4I2Dir(),'qtgui','CCP4ReportWidgets.py'))
     if module is not None:
       clsList = inspect.getmembers(module,inspect.isclass)
       for name,cls in clsList:
          if issubclass(cls,QtGui.QWidget):
            self.reportWidgets[name.lower()] = cls
     #print 'CWebPluginFactory',self.reportWidgets

   def create(self,mimeType,url,argumentNames,argumentValues):
     import re
     from CCP4DataManager import DATAMANAGER
     widget = None
     dataValue = { 'fileName' : self.parent().fileName }
     reportDataObj = None
     #widgetQualifiers = {'editable':False,'styleSheet':'QLabel {font-weight:bold}'}
     widgetQualifiers = {'editable':False }
     arguments = {'ccp4_data_id' : [] }
     for ii in range(0,len(argumentNames)):
       if ['height','width','role'].count(argumentNames[ii]):
          widgetQualifiers[str(argumentNames[ii])] = str(argumentValues[ii])
       elif ['mimeTypeName','type','id'].count(argumentNames[ii]):
          arguments[str(argumentNames[ii])] = str(argumentValues[ii])
       elif argumentNames[ii] == 'ccp4_data_id':
          arguments['ccp4_data_id'].append(str(argumentValues[ii]))
       else:
          dataValue[str(argumentNames[ii])] = str(argumentValues[ii])
     className = re.sub('x-ccp4-widget\/','',str(mimeType))

     #print 'CWebPluginFactory.create dataValue',mimeType,dataValue,className, getattr(self.parent(),'report')

     if className == 'loggraph':
       if getattr(self.parent(),'report') is None:
         widget = None
       else:
         tableList = []
         for tableId in arguments['ccp4_data_id']:
           table = self.parent().report.getEtree(id=tableId)
           if table is not None: tableList.append(table)
         #print 'CWebPluginFactory.create loggraph',arguments['ccp4_data_id'],tableList
         if len(tableList)>0:
           import MGQTmatplotlib
           widget = MGQTmatplotlib.LogGraph(self.parent())
           widget.setDefaultSymbolSize(3)
           openViewer = QtGui.QPushButton('Open graph viewer',widget)
           widget.statusBar.addPermanentWidget(openViewer)
	   self.connect(openViewer, QtCore.SIGNAL("clicked(bool)"),functools.partial(self.openGraphViewer,self.parent().fileName,arguments['ccp4_data_id']))
           for table in tableList:
             try:
               widget.addTableFromEtree(table)
             except:
               print 'ERROR reading table from log file'
           style = """
           QWidget {
           font-size :  10pt;
           }
           """
           widget.setStyleSheet(style)
           widget.setCurrentData(0) 
         else:
           widget = None

     elif self.reportWidgets.get(className,None) is not None:
       if getattr(self.parent(),'report') is None:
         widget= None
       else:
         tableList = []
         for tableId in arguments['ccp4_data_id']:
           if tableId.count(",")>0:
             tables = tableId.split(",")
             for tab2 in tables:
               table = self.parent().report.getEtree(id=tab2)
               if table is not None: tableList.append(table)
           else:
             table = self.parent().report.getEtree(id=tableId)
             if table is not None: tableList.append(table)
         widget = apply (self.reportWidgets[className],[self.parent(),tableList],dataValue)

     else:      
       if self.parent().report is not None and len(arguments['ccp4_data_id'])>0:
         #if report is not None and data_id != '':
         subElement = arguments.get('id',None)
         reportDataObj = self.parent().report.getDataObject(id=arguments['ccp4_data_id'][0],subElement=subElement)
         #print 'CWebPluginFactory.createWebPlugin reportDataObj',reportDataObj
      
       if reportDataObj is None:

         cls = DATAMANAGER().getClass(className)
         #print 'CWebPluginFactory.create cls',className,cls,dataValue
         if cls is not None:
           if DEVELOPER():
             dataObj = cls(value=dataValue,parent=self.parent(),name=arguments.get('id',None))
             widget =DATAMANAGER().widget(parentWidget=self.parent(),model=dataObj,qualifiers=widgetQualifiers)
             if widget is not None: widget.updateViewFromModel()
           else:
             try:
               dataObj = cls(value=dataValue,parent=self.parent(),name=arguments.get('id',None))
               widget =DATAMANAGER().widget(parentWidget=self.parent(),model=dataObj,qualifiers=widgetQualifiers)
               #print 'CWebPluginFactory.create dataObj,widget',dataObj,widget
               if widget is not None: widget.updateViewFromModel()
             except CException as e:
                print e.report()
             except Exception as e:
                e = CException(self.__class__,101,arguments.get('id',''))
                print e.report()
       else:
          if DEVELOPER():
            reportDataObj.setParent( self.parent())
            widget =DATAMANAGER().widget(parentWidget=self.parent(),model=reportDataObj,qualifiers=widgetQualifiers)
          else:
            try:
              reportDataObj.setParent( self.parent())
              widget =DATAMANAGER().widget(parentWidget=self.parent(),model=reportDataObj,qualifiers=widgetQualifiers)
              #print 'CWebPluginFactory.create reportDataObj,widget',reportDataObj,widget
              #if widget is not None: widget.updateViewFromModel()
            except CException as e:
              print e.report()
            except Exception as e:
              e = CException(self.__class__,101,arguments.get('id',''))
              print e.report()

     #print 'CWebPluginFactory',mimeType,url,argumentNames,argumentValues
     #if widget is not None: print 'CWebPluginFactory',widget,widget.parent()
     return widget

   def openGraphViewer(self,fileName,dataIdList=[],clickBool=None):
     #print 'WebPLuginFactory.openGraphViewer',fileName,dataIdList,clickBool
     import CCP4Modules
     argList = []
     for item in dataIdList: argList.extend(['--select',item])
     argList.append(fileName)
     CCP4Modules.LAUNCHER().launch(viewer='loggraph',argList=argList)
     
     
   def plugins(self):
     plugin_list = []

     plugin= QtWebKit.QWebPluginFactory.Plugin()
     plugin.name = "CCP4 test plugin"
     plugin.description = "An example Web plugin written with PyQt."
     mimeType = QtWebKit.QWebPluginFactory.MimeType()
     mimeType.name = "x-ccp4/ccp4_test_plugin"
     mimeType.description = "Test plugin - simple button"
     mimeType.fileExtensions = []
     plugin.mimeTypes = [mimeType]

     plugin_list.append(plugin)
     return plugin_list

