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

import copy
import sys
import os
import re

from coral.log import getLogger
logger=getLogger("coral.modeler.diagram.temanager")
from coral.modeler.editor import Editor
from coral.modeler.window import *
from coral.modeler import iconcache

from qt import *

import traceback
import coral

from coral.modeler import extension



class TextEditorManager(Editor,CoralMDIWindow):     
 
    def __init__(self,parent,extensionRegistry=None):
        Editor.__init__(self)
    
        self.editorTab=parent

        #self.editorTab.connect(self.editorTab, qt.SIGNAL('currentChanged(QWidget *)'), self.focusOnDiagram)
        
        self.parent=parent
        
        CoralMDIWindow.__init__(self,parent)

        coral.getTransactionManager().addObserver(self.onModelChanged)
            
    def focusOnDiagram(self, *args):
        widget = args[0]
        if isinstance(widget, DiagramEditor):
            dgr = widget.getDiagramView().diagram
            if self.focus == dgr:
                return
            self.editorSet.notifyFocusOn(dgr)
            
    def onModelChanged(self,direc):
        return
    
    def focusOn(self,element):        
        self.focus=element

        if self.focus.oclIsKindOf(coral.lang.CoralEx10.FileSystem.File):
            self.addEditorToProperty(element,element.__type__().getPropertyByName("text"),"File "+str(element.name))
        else:
            properties = [p for p in self.focus.__properties__() if not p.isAnonymous() ]
            for p in properties:                   
                if not p.getTarget().isDatatypeDefinition():
                    continue
                if not p.getTarget().isSubclass(coral.String):
                    continue
                if p.isAtMostOne():
                    continue
                for i in range(self.editorTab.count()):
                    page=self.editorTab.page(i)
                    if not isinstance(page,TextEditor):
                        continue

                    if page.element==element and page.property==p:
                        self.editorTab.setCurrentPage(i)
                        return

                    self.addEditorToProperty(element,p)
       
    def addEditorToProperty(self,element,property,label="Text Editor"):
        new=SimpleTextEditor(self.parent)
        
        self.editorTab.addTab(new,label)
        self.editorTab.showPage(new)
        new.focusOn(element,property)
        new.show()

        return new

class TextEditor:
    pass

class SimpleTextEditor(TextEditor,QTextEdit):
    def __init__(self,parent):
        QTextEdit.__init__(self,parent)

        self.element=None
        self.edited=0
        self.propety=None
        self.setWordWrap(QTextEdit.NoWrap)

        # By now we cannot edit the text
        self.setReadOnly(1)
    
    def focusOn(self,element,property):
        self.element=element
        self.property = property
        a = getattr(self.element, self.property.getName())
        s = ""
        if self.property.isAtMostOne():
            s = unicode(a)
        else:
            for i in a:
                s += unicode(i)
                s += "\n"
        self.setText(s)
    
        self.connect(self,SIGNAL('textChanged()'),self.changed)
        self.setCaption("Edit " + self.property.getName())

    def changed(self):
        self.edited=1
        
    def setSlotFromEditor(self):
        if self.edited:
            t = unicode(self.text())
            if self.property.isAtMostOne():
                setattr(self.element, self.property.getName(), t)
            else:
                a = getattr(self.element, self.property.getName())
                a.resetSlot()
                targettype = a.getProperty().getTarget()
                for i in t.rstrip().split("\n"):
                    s = targettype.newAtom()
                    # BUG we would be generic for any datatype
                    # if this was fixed...
                    s.__setString__(i)
                    a.append(s)

