##############################################################
# zNote Bibliography Management Tool v0.6
#
# copyright 2001, 2002 John Maxwell - jmax@portal.ca
#
# This product is licensed under the GNU General Public License. 
# Please see license.txt for details.
#
#  zNote is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published
#  by the Free Software Foundation; either version 2 of the License, 
#  or (at your option) any later version.
# 
#  zNote is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#################################################################


#######################################
# General Formatting Methods
# separated out for maintenance sake
#
# Note that there's not actual output styling
# here -- this module supplies raw material to
# one or other of the Style modules, which 
# which do the actual output formatting   

 
#######################################
# NODE-LEVEL queries

def getChunk(self, myNode, GI):
    "get Text of specified element"
    NL = myNode.getElementsByTagName(GI)
    if len(NL) > 0:
        return self.text(NL[0])
    else:
        return ''

def getAuthors(self, myNode):
    "Authors"
    # need to modify this to handle JR and von
    return myNode.getElementsByTagName('author')

def getEditors(self, myNode):
    "Editors"
    # has to be at this particular level, since
    # we can have editors in different contexts
    retList = []
    for n in myNode.childNodes:
        if n.nodeName == 'editor':
            retList.append(n)
    return retList

def getTrans(self, myNode):
    "Translators"
    # has to be at this particular level
    retList = []
    for n in myNode.childNodes:
        if n.nodeName == 'trans':
            retList.append(n)
    return retList


def text(self, node):
    "Return text from a node"
    if node.firstChild is not None:
        return node.firstChild.nodeValue


def showNotes(self):
    "Display notes element"
    import string
    root = self.REQUEST.PARENTS[0].documentElement
    if root.getElementsByTagName('notes'):
        notesNode = root.getElementsByTagName('notes')[0]
        notesText = self.text(notesNode)
        notesList = string.split(notesText, '\012')
        rs = ''
        for line in notesList:
            rs = rs + line + '<br />\n'
    else:
        rs = ''
    return rs

def notes(self):
    "return the notes node" 
    return self.REQUEST.PARENTS[0].documentElement.getElementsByTagName('notes')[0].firstChild


# this is for the object Titles, not the entries themselves
def composeTitle(self, AuthsList, formDate, formTitle):
    "concatenate a string to serve as object title"
    rawNames = self.getNames(AuthsList)
    cleanTitle = formTitle.split(':')[0]
    titleString = rawNames + ' (' + formDate+ ') ' + cleanTitle
    titleString = titleString.upper()[0] + titleString[1:]
    return titleString
    
    
#########################################################
# Some name-parsing methods:


def names(self, people):
    "Parse First and Last names"
    # people is a nodeList
    A = []
    for p in people:
        # this is a weird as it is in order to make the styling code
        # as economical and readable as possible:
        if p.nodeType == 1:
            A.append({})
            if p.getElementsByTagName("lastname"):
                A[-1]['L'] = self.text(p.getElementsByTagName("lastname")[0])
            else:
                A[-1]['L'] = ''
            if p.getElementsByTagName("firstname"):
                A[-1]['F'] = self.text(p.getElementsByTagName("firstname")[0])
                A[-1]['f'] = self.initials(self.text(p.getElementsByTagName("firstname")[0]))
            else:
                A[-1]['F'] = A[-1]['f'] = ''
    return A


def initials(self, firstname):
    "make initials"
    ## BUG in this: it doesn't do middle names right. and it wipes out a space, I think
    # Damn Hans-Georg anyway.
    names = firstname.split(' ')
    while ' ' in names:
        names.remove(' ')
    inits = []
    try:
        for n in names:
            if '-' in n:
                hyphens = n.split('-')
                hStr = hyphens[0][0]
                for h in hyphens[1:]:
                    hStr = hStr + '-' + h[0]
                inits.append(hStr)
            else:
                inits.append(n[0])
    except:
        return '**** ERROR HERE ****'
    return '. '.join(inits)


def parseName(self, myName):
    "split name into first and last"
    myDict = {}
    if ',' in myName:
        tempList = myName.split(', ')
        myDict['first'] = tempList[1].rstrip() 
        myDict['last'] = tempList[0]
    else:
        tempList = myName.split()
        myDict['first'] = ' '.join(tempList[0:-1])
        try:
            myDict['last'] = tempList[-1]
        except: # what the hell? something not getting passed from the 'new' forms
            myDict['last'] = '*** bug in format.parseName ***'
    return myDict

    
def getNames(self, AuthsList):
    "format multiple names brief string"
    # this is for the object Titles, not the entries themselves
    nameList = []
    for a in AuthsList:
        nameList.append(self.parseName(a)['last'])
    if len(nameList) == 1: return nameList[0]
    elif len(nameList) == 2: return nameList[0] + ' and ' + nameList[1]
    elif len(nameList) > 2: return nameList[0] + ' et. al.'
#    else: return '----'
    else: return str(nameList)


