#!/usr/bin/env python

"""
creates local cache of instance tiddlers to be included in distribution
"""

import sys
import os

import mangler

from tiddlyweb.util import read_utf8_file, write_utf8_file, std_error_message
from tiddlywebplugins.instancer.util import cache_tiddlers
from tiddlywebplugins.twimport import recipe_to_urls

from tiddlywebplugins.console.instance import sources as store_sources


def main(args):
	std_error_message("generating tiddlers from source files")
	generate_tiddler_files()
	std_error_message("caching tiddlers")
	cache_tiddlers("tiddlywebplugins.console")
	return True


def generate_tiddler_files():
	# XXX: adapted from tiddlywebplugins.instancer.util.cache_tiddlers
	sources = {}
	for bag, uris in store_sources.items():
		sources[bag] = []
		for uri in uris:
			if uri.endswith(".recipe"):
				urls = recipe_to_urls(uri)
				sources[bag].extend(urls)
			else:
				sources[bag].append(uri)

	# XXX: adapted from tiddlywebplugins.instancer.util.cache_tiddlers
	tiddlers_path = os.path.join("src", "tiddlers")
	try:
		os.mkdir(tiddlers_path)
	except OSError: # directory exists
		pass

	# XXX: adapted from tiddlywebplugins.instancer.util.cache_tiddlers
	for bag, uris in sources.items():
		bag_path = os.path.join(tiddlers_path, bag)
		try:
			os.mkdir(bag_path)
		except OSError: # directory exists
			pass

		for uri in uris:
			if uri.endswith(".js"):
				type = "javascript"
			elif uri.endswith(".css"):
				type = "css"
			elif uri.endswith(".html"):
				type = "html"
			content_type = "type: text/%s" % type
			if uri.startswith("file://"): # XXX: hack; use twimport's _get_url_handle!?
				uri = uri[7:]
			tiddler = "%s\n\n%s" % (content_type, read_utf8_file(uri))

			filepath = os.path.join(bag_path, os.path.basename(uri))
			filepath = "%s.tid" % filepath
			std_error_message("creating %s" % filepath)
			write_utf8_file(filepath, tiddler)

		recipe = ["tiddler: %s.tid" % os.path.basename(uri) for uri in uris]
		filepath = os.path.join(bag_path, "index.recipe")
		std_error_message("creating %s" % filepath)
		write_utf8_file(filepath, "\n".join(recipe))

	recipe = ["recipe: %s/index.recipe" % bag for bag in sources]
	filepath = os.path.join(tiddlers_path, "index.recipe")
	std_error_message("creating %s" % filepath)
	write_utf8_file(filepath, "\n".join(recipe))


if __name__ == "__main__":
	status = not main(sys.argv)
	sys.exit(status)
