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

from time import gmtime, strftime
import traceback
from coral.modeler.dlg.TransactionBrowserDlg import TransactionBrowserDlg
from coral.modeler.extension import ModelerTool
import coral
import qt

from coral import log
logger=log.getLogger("transactionbrowser")

def plural(x):
    if int(x)==1:
        return ""
    else:
        return "s"
    
class TransactionBrowser(TransactionBrowserDlg,ModelerTool):
    def __init__(self,parent):
        ModelerTool.__init__(self)
        TransactionBrowserDlg.__init__(self,parent)
        self.transactions.setSorting(-1)
        self.commands.setSorting(-1)

        self.connected=0
        self.commands.clear()
        self.timeCache={}
        
        self.doIt()

       
        
    def doIt(self):
        self.connect(self.transactions,qt.SIGNAL("clicked(QListViewItem*)"),
                     self.updateTransaction)
        self.connect(self.transactions,qt.SIGNAL("selectionChanged(QListViewItem*)"),
                     self.updateTransaction)
        if not self.connected:
            coral.getTransactionManager().addObserver(self.onTransaction)
            self.connected=1

        self.onTransaction(None)
        
    def onTransaction(self,t):
        logger.info("Begin TransactionBrowser.onTransaction")
        self.transactions.clear()
      
        tm=coral.getTransactionManager()
        logger.debug("amount"+unicode(tm.getAmountOfTransactions()))
        for i in xrange(tm.getAmountOfTransactions()):            
            tr=tm.getTransaction(i)
            if tr not in self.timeCache:
                self.timeCache[tr]=strftime("%d %b %Y %H:%M:%S", gmtime())
                
            n=qt.QListViewItem(self.transactions,
                                 self.timeCache[tr],"Transaction with "+str(tr.size())+" command"+plural(tr.size()))
            n.transaction=tr
            self.transactions.insertItem(n)
            if tr==tm.getCurrentTransaction():
                self.transactions.setSelected(n,1)
        logger.info("End TransactionBrowser.onTransaction")
        
    def updateTransaction(self,t):
        logger.info("updateTransaction")
        if t is None:
            return
        
        self.commands.clear()

        
        tr=t.transaction

        for c in tr:
            name=c.__class__.__name__
            element=""
            new=""
            if isinstance(c,coral.ChangeElementPrimitiveCommand):
                name="Atom Change"
                element=str(c.getNewAtom())
            elif isinstance(c,coral.ElementNewCommand):
                name="New Element"
                element=str(c.getNewElement())
            elif isinstance(c,coral.ElementChangeSlotCommand):
                s = c.getSlot()
                p = s.getProperty()
                name="Property Change"
                element = unicode(s.getElement())
                new = p.getName() + " = "
                ed = p.getTarget()
                if ed.isDatatypeDefinition():
                    if p.isAtMostOne():
                        new += unicode(s[0])
                    else:
                        new += " [ " + ", ".join([unicode(x) for x in s]) + " ] "
                else:
                    new += unicode(c.getSlot())
            elif isinstance(c, coral.ProjectChangeCommand):
                name = "Project Change"
                element = str(c.getAtom())
                new = str(c.getOldProject())
            elif isinstance(c, coral.NewProjectCommand):
                name = "New Project"
                element = str(c.getNewProject())
                new = str(c.getNewProject().getFilename())
            elif isinstance(c, coral.ProjectNameChangeCommand):
                name = "Project Name Change"
                p = c.getProject()
                element = str(p)
                new = c.getOldHrefFilename() + " : " + c.getOldFilename()
            else:
                name = "UNKNOWN FIX THIS " + str(c)
            self.commands.insertItem(qt.QListViewItem(
                self.commands,
                    name,element,new))


