#!/usr/pkg/bin/python2.7
#----------------------------------------------------------------------------
# Project Name: MOSS
# File Name: template.py
# Description: Processing template routine.
#
# Created: 2004. 06. 20
# RCS-ID: $Id: template.py,v 1.19 2004/10/07 08:13:16 myunggoni Exp $
# Copyright: (c) 2004 by myunggoni
# License: GNU General Public License
# Author: Myung-Gon Park <myunggoni@users.kldp.net>
#----------------------------------------------------------------------------
from htmltmpl import TemplateManager, TemplateProcessor, TemplateError
import urllib
import string

class Template:
	def __init__(self, template_file):
		# Compile or load already precompiled template.
		try:
			self.template = TemplateManager().prepare(template_file)
		except TemplateError:
			raise SystemExit

		self.template_proc = TemplateProcessor()

	def generate(self, fp, url, subdirs, songs):
		parts = string.split(url, '/')
		curdir = urllib.unquote(parts.pop(-1))
		prevdir = string.join(parts, '/')

		if url == '/':
			playall = url + "playall.m3u"
			playrecursively = url + "playrecursively.m3u"
		else:
			playall = url + '/' + "playall.m3u"
			playrecursively = url + '/' + "playrecursively.m3u"
		
		if not curdir == '' and prevdir == '':
			prevdir = '/'

		for i in range(len(songs)):
			try:
				for key, value in songs[i]["fileinfo"].items():
					songs[i][key] = value

				songs[i]["samplerate"] = "%d " % songs[i]["samplerate"] + "Hz"
				songs[i]["bitrate"] = "%d " % songs[i]["bitrate"] + "Kbps"
				songs[i]["filesize"] =  "%.1f " % (songs[i]["filesize"]) + "Mb"
			except AttributeError:
				songs[i]["samplerate"] = "Unknown"
				songs[i]["bitrate"] = "Unknown"
				songs[i]["filesize"] = "Unknown"

		self.template_proc.set("Songs", songs)
		self.template_proc.set("Subdirectory", subdirs)
		self.template_proc.set("currentdirectory", curdir)
		self.template_proc.set("previousdirectory", prevdir)
		self.template_proc.set("currenturl", url)
		self.template_proc.set("currentsongs", len(songs))
		self.template_proc.set("playall", playall)
		self.template_proc.set("playrecursively", playrecursively)

		fp.write(self.template_proc.process(self.template))
