# This file is part of the Coral project.
# Please read the copyright notice in the LICENSE file.

import qt
import sys
import copy
import string
import coral

from coral import configuration

from coral.modeler.coralmodeler import CoralModeler
from coral.modeler import iconcache
from coral.log import getLogger

from coral.modeler import  action,CoralAction

class CoralTabBar(qt.QTabBar):

    def mousePressEvent(self,e):
        if e.button() == qt.Qt.RightButton:
            print "mpe",e
            print "TODO: show context menu for tabs"

        return qt.QTabBar.mousePressEvent(self,e)
        
class CoralTabWidget(qt.QTabWidget):

    def __init__(self,parent):
        qt.QTabWidget.__init__(self,parent)

        self.setTabBar(CoralTabBar(self))
        self.closeB = qt.QToolButton(self,'close')
        self.closeB.setPixmap(iconcache.getIcon("exit"))
        self.setCornerWidget(self.closeB)
        self.connect(self.closeB,qt.SIGNAL('clicked()'),self.closeCurrentPage)
        self.connect(self,qt.SIGNAL('currentChanged(QWidget *)'),self.currentChanged)
        self.closeB.hide()
        
        #self.connect(self,qt.SIGNAL('clicked()'),self.clicked)

   
    def currentChanged(self,page):
        if isinstance(page,CoralActionHandler):
            page.setActive()
        
    def closeCurrentPage(self):
        if self.count():
            self.closePage(self.currentPage())

    def addTab(self,*args):
        self.closeB.show()
        args=[self]+list(args)
        return apply(qt.QTabWidget.addTab,args)
    
    def closePage(self,page):        
        page.close()
        self.removePage(page)
        if not self.count():
            self.closeB.hide()
            pass

class CoralActionHandler:
    """Every subsystem that wants to export actions to the
    GUI or shell scripting facility must subclass CoralActionHandler.
    It will call self.initActions() which should return a list
    of CoralActions."""
    def __init__(self):
        self.menuDefinition=[]
        self.privateMenuBar=[]
        self.actionTypes=[]
            
        for a in self.initActions():

            # if the action handler is string based "shell.open"
            # we declare ourselves as the handler of that type
          
            a=action.__declareAction__(a)

            if type(a.handler)==type(""):
                l=string.split(a.handler,".")
                if len(l)>1:
                    if l[0] not in self.actionTypes:
                        self.actionTypes.append(l[0])


        self.setActive()

        
    def setActive(self):
        """Sets the actions of self to be the active ones
        Actions have global names, meaning that e.g. two Shell
        windows compete whose actions are currently active."""
        for a in self.actionTypes:
            action.setCurrentHandler(a,self)

        #print "<->"*20
        #print "setActive self=",self
        
    def setInactive(self):
        pass

    
    def initActions(self):
        """The actions that this object supports."""
        return []

    def bindActions(self):
        """Something to do with a popup menu."""
        for m in self.menuDefinition:
            name = "coral-menu-" + m[0]
            for option in m[1]:
                name += "__" + option
            popUp=qt.QPopupMenu( None, name )
            for option in m[1]:
                if not action.__exists__(option):
                    raise "bindActions: unknown action "+option
                action[option].addTo(popUp)
            self.privateMenuBar.append(("&"+m[0],popUp))
    
class CoralMDIWindow(CoralActionHandler):

    def __init__(self,parent):
        CoralActionHandler.__init__(self)

    
    def doNothing(self):
        pass

    def editCut(self):
        pass


    def editCopy(self):
        pass

    def editPaste(self):
        pass

    def editDelete(self):
        pass

    def editSelectAll(self):
        pass

    def close(self,x=0):
        pass
     
    def mainWindow(self):
        return CoralModeler.getInstance().getQtApp().mainWidget()
        
class CoralMainWindow(qt.QMainWindow,CoralActionHandler):
    
    def __init__(self):      
        self.config=configuration.getCoralConfiguration()
        self.log=getLogger("CoralMainWindow")
        qApp=CoralModeler.getInstance().getQtApp(sys.argv)

        if self.config.dGet(["GUI","style"])=="Platinum":
            qApp.setStyle(qt.QPlatinumStyle())
        if self.config.dGet(["GUI","style"])=="Motif":
            qApp.setStyle(qt.QMotifStyle())

        #qApp.setFont(
        #    qt.QFont(self.config.dGet(["GUI","font_family"],"Helvetica"),
        #             int(self.config.dGet(["GUI","font_size"],"10")))
        #             )
        
        qt.QMainWindow.__init__(self)
        CoralActionHandler.__init__(self)
            
        self.setCaption("Coral version " + str(coral.version) )
        self.statusBar().message("")
        self.statusBar().setSizeGripEnabled(1)

        self.printer=None

        self.initUI()

        
    def initMenu(self):
        return [
            ( "File",( "close","quit" )  )
            ]
            

    def initActions(self):
        return [    CoralAction(self,"quit","application.quit", "&Quit",
                        qt.QIconSet(iconcache.getIcon("quit")),
                        qt.Qt.CTRL+qt.Qt.Key_Q),
                    CoralAction(self,"close","application.close","&Close",
                        qt.QIconSet(iconcache.getIcon("closeMenu")),
                        qt.Qt.CTRL+qt.Qt.Key_W),               
            ]
    
    def initUI(self):
        self.setDockEnabled(qt.Qt.DockTop,1)        
        self.toolBar=qt.QToolBar(self)
                
        self.menuDefinition=self.initMenu()
        self.rebindActions()

        self.setWorkspace()
        
    def rebindActions(self):
        self.menuBar().clear()

        for m in self.privateMenuBar:
            m[1].destroy()

        self.privateMenuBar=[]
        
        self.bindActions()
       
        
        idx = 0
        for m in self.privateMenuBar:
            self.menuBar().insertItem(m[0], m[1], idx)
            idx += 1
            
        self.menuBar().show()
        
        

   
    def setWorkspace(self):
        self.workspace=qt.QFrame(self)
        self.workspace.setSizePolicy(
            qt.QSizePolicy(qt.QSizePolicy.Expanding,qt.QSizePolicy.Expanding))
        self.setCentralWidget(self.workspace)
        self.workspace.show()

    def main(self, loop=1):
        self.enterQtLoops= loop
        if loop:
            self.exec_loop()
        else:
            #while
                
            self.processEvents()
            
    def exec_loop(self):
        CoralModeler.getInstance().getQtApp().exec_loop()

    def processEvents(self):
        CoralModeler.getInstance().getQtApp().processEvents()

    def quit(self):
        CoralModeler.getInstance().getQtApp().setMainWidget(self)
        CoralModeler.getInstance().quit()
        
