#! /usr/bin/env python
'''

Support stuff for snapper.py, providing lots of W3C style support.

The division may not be as clean as we would like


'''
__version__ = "$Revision: 1.3 $"

import os
import os.path
from debugtools import debug

class Defaults:

    def _compute_h1Title(self, props):
        try:
            return props["titlePrefix"]+props["shortTitle"]
        except KeyError:
            return props["shortTitle"]

    def _compute_htmlTitle(self, props):
        try:
            return props["titlePrefix"]+"<br />"+props["shortTitle"]
        except KeyError:
            return props["shortTitle"]





    def _default_doctype(self):
        return doctypes[self.maxdoctypecode]

    def _compute_maxdoctypecode(self, props):
        if props.ed_only:
            return "ED"
        else:
            return props.doctypecode
    
    #def _compute__dateCode(self, props):
    #    return props._dateCode

    #@property
    #def commentsDue(self):
    #    return self.snapshot.commentsDue

    @property
    def hasPrevious(self):
        return hasattr(self, 'pdateCode') or hasattr(self.snapshot, 'pdateCode')
    
    @property
    def pdateCode(self):
        return self.snapshot.pdateCode

    @property
    def _dateName(self):
        return self.snapshot._dateName

    def _compute_directory(self, props):
        return props.versioncode
    
    def _compute_versioncode(self, props):
        return (props.maxdoctypecode+"-"+
                props.groupShortname+"-"+
                props.shortname+"-"+
                props.dateCode)

    def _default_pversioncode(self):
        assert self.hasPrevious
        return (self.maxdoctypecode+"-"+
                self.snapshot.group.shortname+"-"+
                self.shortname+"-"+
                self.pdateCode)

    @property
    def versionPrefixURL(self):
        #  can't easily do relative URLs, because we tell the
        #  users these URLs...
        if self.maxdoctypecode == 'ED':
            return self.snapshot.group.draftsURL
        if self.maxdoctypecode == 'WD':
            return "http://www.w3.org/TR/2008/"
        raise RuntimeError, 'dont know how to make version URL'        
        
    @property
    def thisVersion(self):
        return self.versionPrefixURL+self.versioncode+"/"


    def _default_previousVersion(self):
        return self.versionPrefixURL+self["pversioncode"]+"/"

    @property
    def latestURL(self):
        if self.maxdoctypecode == 'ED':
            prefix = self.versionPrefixURL
        if self.maxdoctypecode == 'WD':
            prefix = "http://www.w3.org/TR/"   # not quite the same!
        return prefix+self.snapshot.group.shortname+"-"+self.shortname+"/"

    @property
    def wikiPageURL(self):
        return self.snapshot.group.wikiURL+self.wikiPageName
    
    @property
    def inLineCredit(self):
        if self.authors:
            return ", ".join([person.name for person in self.authors])
        if len(self.editors) == 1:
            ed = "editor"
        else:
            ed = "eds"
        return ", ".join([person.name for person in self.editors]) + ", " + ed



    
    def _default_css(self):
        result = """<style type="text/css">
   .editsection { display: none; }
</style>
"""
        for stylesheet in self.stylesheets:
            result+=('''<link rel="stylesheet" type="text/css" href="%s" />\n'''
                     % stylesheet)
        result += """<link rel="stylesheet" type="text/css" href="http://www.w3.org/StyleSheets/TR/W3C-%(maxdoctypecode)s" />\n""" % self

        return result



    @property
    def credits(self):
        result = u"<dl>"
        for tag in ('Author', 'Editor', 'Contributor'):
            attr = tag.lower()+"s"
            people = getattr(self, attr)
            if people:
                if people > 1:
                    result += u"<dt>%ss:</dt>" % tag
                else:
                    result += u"<dt>%s:</dt>" % tag
                for person in people:
                    result += u"<dd>"+person.line+u"</dd>\n"
        result += u"</dl>"
        return result

    @property
    def formats(self):
        return '''<p>This document is also available in these non-normative formats: <a href="all.pdf">PDF version</a>.</p>'''

    @property
    def referenceText(self):
        """Return standard text that one can use in a References
        section to refer to this version of this document
        """
        result = u"""<span><cite><a class="external text" href="%(thisVersion)s">%(refTitle)s</a></cite> %(inLineCredit)s. W3C %(doctype)s, %(_dateName)s, <a class="external free" href="%(thisVersion)s">%(thisVersion)s</a>.  Latest version available at <a class="external free" href="%(latestURL)s">%(latestURL)s</a>.</span>""" % self
        return result

    @property
    def numDocs(self):
        return len(self.snapshot.pages)

    @property
    def allDocs(self):
        result = "<ol>\n"
        for page in self.snapshot.pages:
            if page is self:
                thisOne = "(this document)"
            else:
                thisOne = ""
            result += u"""<li><a href="%(thisVersion)s">%(shortTitle)s</a> """%page + thisOne+"</li>\n"
        result += "</ol>\n"
        return result

    @property
    def sotdSOD(self):
        if len(self.snapshot.pages) < 2:
            return ""
        
        result = """
<h4 class="no-toc no-num" id="related">Set of Documents</h4>

<p>This document is being published as one of a set of %(numDocs)s documents: </p>
%(allDocs)s
"""%self
        return result

    @property
    def pleaseCommentText(self):
        if self.pleaseComment is not None:
            
            return self.pleaseComment
        else:
            return """
        <h4 class="no-toc no-num" id="please">Please Comment By %(commentsDue)s</h4>

    <p>The <a class="http" href="%(homeURL)s"
    >%(name)s</a> seeks
    public feedback on %(commentOn)s.  Please send your
    comments to <a class="mailto"
    href="mailto:%(commentsList)s@w3.org"
    shape="rect">%(commentsList)s@w3.org</a> (<a class="http"
    href="http://lists.w3.org/Archives/Public/%(commentsList)s/"
    shape="rect">public archive</a>).  If possible, please offer
    specific changes to the text that would address your
    concern.  You may also wish to check the <a
    href="%(wikiPageURL)s">Wiki
    Version</a> of this document for internal-review comments and changes being
    drafted which may address your concerns. </p>""" % self 
    
    @property
    def diffURL(self):
        return self.versionPrefixURL+self.diffFile

    @property
    def diffFile(self):
        return self.directory+"/diff-since-"+self.pdateCode
    
    @property
    def diffText(self):
        if self.maxdoctypecode == 'ED':
            return u' (<a href="%s">color-coded diff</a>)' % self.diffURL
        else:
            return ""

    @property
    def labelForLatest(self):
        if self.maxdoctypecode == 'ED':
            return "Latest editor's draft"
        else:
            return "Latest version"
        
    @property
    def versionStuff(self):
        result = u"""
<dl>
<dt>This version:</dt>
<dd><a id="this-version-url" href="%(thisVersion)s">%(thisVersion)s</a></dd>
<dt>%(labelForLatest)s:</dt>
<dd><a href="%(latestURL)s">%(latestURL)s</a></dd>
""" % self
        if self.hasPrevious:
           result += u"""
<dt>Previous version:</dt>
<dd><a href="%(previousVersion)s">%(previousVersion)s</a>%(diffText)s</dd>
""" % self
        result += u"</dl>"
        return result



################################################################

def date(datecode):
    """
       >>> dateCode(date('20080101'))
       '20080101'
       >>> dateCode(date('2008-01-01'))
       '20080101'
       >>> dateName(date('20081202'))
       '2 December 2008'
       
    """
    if datecode[4] == "-":
        assert len(datecode) == 10
        return datetime.date(int(datecode[0:4]),
                             int(datecode[5:7]),
                             int(datecode[8:10]))
    else:
        assert len(datecode) == 8
        return datetime.date(int(datecode[0:4]),
                             int(datecode[4:6]),
                             int(datecode[6:8]))

def dateName(date):
    s = date.strftime("%d %B %Y")
    if s[0] == "0":
        s = s[1:]
    return s

def dateCode(date):
    return date.strftime("%Y%02m%02d")


################################################################

main_template = u"""<?xml version="1.0" encoding="UTF-8"?><!--*- nxml -*-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <title>%(htmlTitle)s</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  %(css)s
  %(main_javascript)s
</head>
<body>

<div class="head">
<a href="http://www.w3.org/"><img alt="W3C" height="48"
src="http://www.w3.org/Icons/w3c_home" width="72"/></a><h1 style="clear:both" id="title">%(h1Title)s</h1>

<h2 id="W3C-doctype">W3C %(doctype)s %(_dateName)s</h2>

%(versionStuff)s

%(credits)s

<hr />

<p class="copyright"><a href="http://www.w3.org/Consortium/Legal/ipr-notice#Copyright">Copyright</a> &copy; 2008 <a href="http://www.w3.org/"><acronym title="World Wide Web Consortium">W3C</acronym></a><sup>&reg;</sup> (<a href="http://www.csail.mit.edu/"><acronym title="Massachusetts Institute of Technology">MIT</acronym></a>, <a href="http://www.ercim.org/"><acronym title="European Research Consortium for Informatics and Mathematics">ERCIM</acronym></a>, <a href="http://www.keio.ac.jp/">Keio</a>), All Rights Reserved. W3C <a href="http://www.w3.org/Consortium/Legal/ipr-notice#Legal_Disclaimer">liability</a>, <a href="http://www.w3.org/Consortium/Legal/ipr-notice#W3C_Trademarks">trademark</a> and <a href="http://www.w3.org/Consortium/Legal/copyright-documents">document use</a> rules apply.</p>

</div>
<hr/>
<h2><a id="abstract" name="abstract">Abstract</a></h2>

<div>
%(abstract)s
</div>

<h2 class="no-toc no-num">
<a id="status" name="status">Status of this Document</a>
</h2>
    
<h4 class="no-toc no-num" id="may-be">May Be Superseded</h4>
    
<p><em>This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the <a href="http://www.w3.org/TR/">W3C technical reports index</a> at http://www.w3.org/TR/.</em></p>
    
%(sotdSOD)s    

%(snapshotStatusExtra)s

%(statusExtra)s

%(pleaseCommentText)s
    
<h4 class="no-toc no-num" id="no-endorsement">No Endorsement</h4>
    
<p><em>Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.</em></p>
    
<h4 class="no-toc no-num" id="patents">Patents</h4>
    
<p><em>This document was produced by a group operating under the <a href="http://www.w3.org/Consortium/Patent-Policy-20040205/">5 February 2004 W3C Patent Policy</a>. W3C maintains a <a rel="disclosure" href="http://www.w3.org/2004/01/pp-impl/%(id)d/status">public list of any patent disclosures</a> made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains <a href="http://www.w3.org/Consortium/Patent-Policy-20040205/#def-essential">Essential Claim(s)</a> must disclose the information in accordance with <a href="http://www.w3.org/Consortium/Patent-Policy-20040205/#sec-Disclosure"> section 6 of the W3C Patent Policy</a>.</em></p>

<hr title="Separator After Status Section" />

%(docbody)s

</body>
</html>
"""


main_javascript = """
<script type="text/javascript">/*<![CDATA[*/
/*
	Written by Jonathan Snook, http://www.snook.ca/jonathan
	Add-ons by Robert Nyman, http://www.robertnyman.com
	Author says "The credit comment is all it takes, no license. Go crazy with it!:-)"
	From http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
*/

function getElementsByClassName(oElm, strTagName, oClassNames){
	var arrElements = (! (! (strTagName == "*") || ! (oElm.all)))? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var arrRegExpClassNames = new Array();
	if(typeof oClassNames == "object"){
		for(var i=0; !(i>=oClassNames.length); i++){ /*>*/
			arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
		}
	}
	else{
		arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
	}
	var oElement;
	var bMatchesAll;
	for(var j=0; !(j>=arrElements.length); j++){ /*>*/
		oElement = arrElements[j];
		bMatchesAll = true;
		for(var k=0; !(k>=arrRegExpClassNames.length); k++){ /*>*/
			if(!arrRegExpClassNames[k].test(oElement.className)){
				bMatchesAll = false;
				break;
			}
		}
		if(bMatchesAll){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

function set_display_by_class(el, cls, newValue) {
   var e = getElementsByClassName(document, el, cls);
   if (e != null) {
      for (var i=0; !(i>=e.length); i++) {
        e[i].style.display = newValue;
      }
   }
}

function set_display_by_id(id, newValue) {
   var e = document.getElementById(id);
   if (e != null) {
     e.style.display = newValue;
   }
}
/*]]>*/
</script>
 """

defaults = Defaults()
defaults.documentTemplate = main_template
defaults.main_javascript = main_javascript

