'''
html.py - HTML functions

(c) 2005 Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>

 This program 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.

'''

import os,re
from StringIO import StringIO
from aglib import find_service

class table:
  def __init__(self,params=''):
      self.TAB=StringIO()
      self.TAB.write("<table %s>" % params)
      self.tr='<tr>'
      self.cols={}
  def column(self,n):
      if self.cols.get(n):
        return ' '+self.cols.get(n)
      elif self.cols.get(0):
        return ' '+self.cols.get(0)
      else:
        return ''
  def add(self,*args):
      self.TAB.write(self.tr)
      n=0
      for col in args:
        n+=1
        self.TAB.write("<td%s>%s</td>" % (self.column(n),col))
      self.TAB.write("</tr>\n")
  def addhdr(self,*args):
      self.TAB.write(self.tr)
      n=0
      for col in args:
        n+=1
        self.TAB.write("<th%s>%s</th>" % (self.column(n),col))
      self.TAB.write("</tr>\n")
  def __str__(self):
      self.TAB.write("</table>\n")
      return self.TAB.getvalue()

class page:
  TAILER='</body>\n</html>\n'
  def __init__(self,template=''):
      self.io=StringIO()
      self.write(template)
  def body_params(self,params):
      data=self.io.getvalue()
      self.io=StringIO()
      self.io.write(data.replace('<body>','<body %s>' % params))
  def write(self,data):
      self.io.write(data)
  def getvalue(self):
      return self.io.getvalue()+self.TAILER
  def h1(self,data):
      self.io.write('<h1>%s</h1>' % data)

def error(txt):
    pg=page()
    pg.h1(txt)
    return pg.getvalue()

def errrow(txt,style='background: red; color: white',td='align="center"'):
    return '<tr style="%s"><td %s>%s</td></tr>\n' \
      % (style,td,txt)

def msgrow(txt,style='background: green; color: white',td='align="center"'):
    return '<tr style="%s"><td %s>%s</td></tr>\n' \
      % (style,td,txt)

def errtab(txt,style='background: red; color: white'):
    t=table('style="border: none"')
    t.tr='<tr style="%s">' % style
    t.td='<td align="center">'
    t.add(txt)
    return str(t)

def select(name,items,selected=None):
    r='<select name="%s">\n' % name
    for k,v in items:
      if k==selected:
        r+='<option value="%s" selected="selected">%s</option>\n' % (k,v)
      else:
        r+='<option value="%s">%s</option>\n' % (k,v)
    return r+'</select>\n'

def specialchars(txt):
    '''HTML-ize plain text'''
    return txt.replace('&','&amp;').replace('>','&gt;').replace('<','&lt;')
