# some functions from my _code.py
# (c) 2005 Jiri Baum

import os, socket, xml.parsers.expat

def markup_underline(text, meta):
    """ Underlined text.

        Example:
           What [underline was] that? """
           
    return u'<u>'+text+u'</u>'

def markup_comment(*args):
  """ Comment does nothing. You can use it to make notes for yourself
  which won't show up on the page (not even in "view source"; however,
  it *will* show up in the "show code" action). """
  return u""

def markup_hide(*args):
  """  Hide does nothing. You can use it to make notes for yourself which
  won't show up on the page (not even in "view source"; however, it *will*
  show up in the "show code" action). """
  return u""


def markup_irate_track(text, meta):
  """ The track currently playing in iRATE.

  If no track is playing, prints "-". """
  
  def get_track():
    class got_it:
      def __init__(me, name, attrib):
	me.name = name; me.attrib = attrib

    def start_elem(name, attrib):
      raise got_it(name, attrib)

    p = xml.parsers.expat.ParserCreate()
    p.StartElementHandler = start_elem

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('localhost', 12473))
    s.sendall("""
      <Command type="currenttrack"/>
    """)
    try:
      while 1:
	data = s.recv(1024)
	p.Parse(data)
    except got_it, e:
      res = e.attrib
    s.close()
    return res

  try:
    track = get_track()
    track['title'] = quote_html(track['title'])
    track['artist'] = quote_html(track['artist'])
    return u'<a href="%(url)s">%(title)s by %(artist)s</a>'%track
  except:
    return u'-'

def markup_pom(*args):
  """ The phase of the moon, as displayed by pom(6). """
  return os.popen("/usr/games/pom", "r").read()

def handle_random(name, query):
    """ Go to a random entry in a blog. """
    import random

    if 'hasname' in query:
        name = unquote_paranoid(query.get('name',u''))

    names = list_names(name)

    return make_redirect(random.choice(names)[1])

