#Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
#history www.reportlab.co.uk/rl-cgi/viewcvs.cgi/rlextra/forms/qwidget.py

from qbase import QField

_JSFiles=[]
def getJSFiles(N,fmt=None): 
    t = []
    global _JSFiles
    for n in N:
        if fmt: n = fmt(n)
        if n not in _JSFiles:
            t.append(n)
            _JSFiles.append(n)
    return '\n'.join(t)

#   aText is the array js text, should be used for creating a js file with name aTextFN
#   hText is the html text needed to import the aText
#   iText is the js text that needs to go into the object creation js
#   lText is the js text we need to add to the load function
#   dText is the html text we need to add to the HTML to display the function
#   uText is the js text we need to add to the unload function
#   vText is the js for form validation
class QWidget(QField):
    def __init__(self,_kw,**kw):
        QField.__init__(self)
        for D in (kw,_kw):
            for k,v in D.items(): self.__dict__[k] = v
        self.postInit()

    def setChildDict(self,A,useFmt=None,clear=1):
        '''A is the set of attributes to transfer/initialise in childDict'''
        if clear: self.childDict = {}
        for a in A:
            if useFmt: a = self._fmt(a)
            if self.__dict__.has_key(a):
                v = self.__dict__[a]
                del self.__dict__[a]
            else:
                v = ''
            self.childDict[a] = v

    def postInit(self):
        pass

    def getAText(self):
        if not hasattr(self,'aText'): self.aText = None
        return self.aText

    def getATextFN(self):
        self.aTextFN = None
        return self.aTextFN

    def saveAFile(self):
        fn = self.getATextFN()
        if fn: raise NotImplementedError, 'Need to implement saveAFile'

    def getHText(self):
        if hasattr(self,'jsFileName'):
            L = ['<script language="Javascript" src="%(httpDir)s/%(jsFileName)s.js"></script>']
            self.hText = getJSFiles(L,fmt=self._fmt)
        else:
            self.hText = ''
        return self.hText

    def getLText(self):
        self.lText = ''
        return self.lText

    def getUText(self):
        self.uText = ''
        return self.uText

    def getIText(self):
        self.iText = ''
        return self.iText

    def getSText(self):
        self.sText = ''
        return self.sText

    def getDText(self):
        self.dText = ''
        return self.dText

    def getVText(self):
        self.vText = ''
        return self.vText

    def populateDict(self, D, useStr): # removed 3rd argument
        pfx = self._get_pfxname()
        for k,v in self.childDict.items():  # AR - this must be a significant typo?
            if v not in ['',None]:
                if useStr: v = str(v)
                D[pfx+k] = v

    def setTextDictionary(self, D):
        K = self.childDict.keys()
        for k, v in self.deFixDict(D)[None].items():
            if k in K: self.childDict[k] = v

    def _fmt(self,fmt):
        return fmt % self.__dict__

    def _get_pfxname(self):
        self._pfxname = (self.prefix and self.prefix+'.' or '')+self.name+'.'
        return self._pfxname

    def __getattr__(self,name):
        "Return stuff in childDict.  Allows self.FundCode_1 notation which is nice in prep file"
        try:
            return self.childDict[name]
        except KeyError:
            raise AttributeError('Attribute %s not found in %s widget or its child dictionary' % (name,self.__class__.__name__))

    def __str__(self):
        "Inherited behaviour of getTextValue is wrong for compound widgets"
        return repr(self)

    def makeHtml(self):
        return self.getDText()

    def makeHiddenField(self):
        pfx = self._get_pfxname()
        html = []
        for k,v in self.childDict.items():
            if v not in [None, '']:
                html.append('<input type="hidden" name="%s" value="%s">' % (pfx+k,v))
        return ''.join(html)

    def buildTestHTML(self,pagename='test_fs.html'):
        self.saveAFile();
        self.getHText();
        self.getIText();
        self.getLText();
        self.getDText();
        self.getUText();
        self.getVText();
        open(pagename,'w').write(self._fmt('''<html><head>%(hText)s
<script language="JavaScript">
<!--
%(iText)s
function _RL_VALIDATE(){
    var msg;
    msg = ''+%(vText)s;
    if(msg){
        alert(msg);
        return false;
        }
    return true;
    }
function _RL_ONLOAD(){
    %(lText)s
    }
function _RL_ONUNLOAD(){
    %(uText)s
    }
//-->
</script>
</head>
<body onload="_RL_ONLOAD();" onunload="_RL_ONUNLOAD();">
<form method="post" action="http://server.reportlab.com/cgi-bin/echo.cgi" onsubmit="return _RL_VALIDATE();">
<table>
%(dText)s
<tr><td colspan=3>&nbsp;</td></tr>
<tr><td colspan=2><td><input type=submit value="submit"></td></tr>
</table>
</form>
</body>
</html>'''))

class DynamicQWidget(QWidget):
    def __init__(self,**kw):
        QWidget.__init__(self,kw)
        self.setChildDict(())
