#!/usr/bin/env python
from os import path
from glob import glob
from xml.dom.minidom import Document
import re
import urllib

from_dir = path.expanduser('~/.gnome2/gthumb/collections/')
to_dir = path.expanduser('~/.local/share/gthumb/catalogs/')

for inpath in glob(path.join(from_dir, '*.gqv')):
    if path.basename(inpath) == 'Search Result.gqv': continue
    print "Converting file: " + inpath
    infile = open(inpath, 'r')

    doc = Document()
    catalog = doc.createElement("catalog")
    catalog.setAttribute("version", "1.0")
    doc.appendChild(catalog)
    files = doc.createElement("files")
    catalog.appendChild(files)

    for line in infile:
        # Skip comment lines
        if re.match('\s*#', line): continue
        # Remove quotes
        uri = re.match('"(.*)"\s*$', line).group(1)
        if uri:
            uri = urllib.unquote(uri)
            # Fix broken URLs and skip invalid
            if re.search('[^[:print:]]', uri):
                print 'Found non-printable characters in URI: ', uri

            if re.match('file://', uri):
                pass
            elif re.match('/', uri):
                uri = 'file://' + uri
            else:
                continue

            file = doc.createElement("file")
            file.setAttribute("uri", uri)
            files.appendChild(file)

    infile.close
    outpath = path.join(to_dir, path.splitext(path.basename(inpath))[0] + '.catalog')
    if path.lexists(outpath):
        print 'Refusing to overwrite existing file: ' + outpath
    else:
        print 'Writing to file: ' + outpath
        outfile = open(outpath, 'w')
        doc.writexml(outfile, addindent="  ", newl="\n", encoding="UTF-8")
        outfile.close

    doc.unlink
