#!/usr/bin/env python

###############################################################################
#
# Copyright (C) 2010 Karl Ostmo
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
###############################################################################
#
# Author: Karl Ostmo
# Date: Feb. 23, 2010
# Version: 1.1
# Description: Produces a histogram plot of orders from Google Checkout data
#
###############################################################################

import os
GTHUMB_COLLECTIONS_DIRECTORY = "~/.local/share/gthumb/catalogs"

# NOTE: This script is designed for gThumb version 2.11.  Versions 2.10 and earlier use the GQView "flat file" format.
# =============================================================================

def make_library(gthumb_library_name):
	import os, shutil
	gthumb_library_path = os.path.join(os.path.expanduser(GTHUMB_COLLECTIONS_DIRECTORY), gthumb_library_name)
	if os.path.exists(gthumb_library_path):
		shutil.rmtree(gthumb_library_path)
	os.mkdir(gthumb_library_path)

	return gthumb_library_path

# =============================================================================
def write_catalog(image_paths, collection_name, library_path=None):

	import os
	collection_path = collection_name + ".catalog"
	if library_path:
		collection_path = os.path.join(library_path, collection_path)

	import urllib
	from xml.dom.minidom import Document

	# Create the minidom document
	doc = Document()

	# Create the <catalog> base element
	catalog_element = doc.createElement("catalog")
	catalog_element.setAttribute("version", "1.0")
	doc.appendChild(catalog_element)

	# Create the main <files> element
	files_element = doc.createElement("files")
	catalog_element.appendChild(files_element)

	for path in image_paths:
		# Create a <file> element
		file_element = doc.createElement("file")
		file_element.setAttribute("uri", "file://" + urllib.quote( os.path.abspath(path) ))
		files_element.appendChild( file_element )

	f = open(collection_path, "w")
	doc.writexml(f, addindent="\t", newl="\n")
	f.close()

# =============================================================================
def write_and_open_catalog(image_paths, library_name, catalog_name):

	gthumb_library_path = make_library(library_name)
	write_catalog(image_paths, catalog_name, gthumb_library_path)
	os.system("gthumb \"catalog:///%s/%s.catalog\"" % (library_name, catalog_name))

