#!/usr/bin/env python2
# -*- mode:python -*-

import sys
import os
import zipfile
import libxml2
import libxslt
import tempfile
import importlib

# Get origin location for loading supplemental files:
__location__ = '/'.join(os.path.realpath(__file__).split('/')[:-1])
sys.path.append(__location__)
from heredocs import *

g_transformxsl = os.path.join(__location__, "transform.xsl")

g_infile = None
g_outfile = None

def show_usage():
    print "Usage:"
    print "./pxml2ods <xml source file> <ods filename>"
    print "example: ./pxml2ods names_list.xml names.ods\n\n"
    

def set_global_filenames():
    global g_infile, g_outfile

    argcount = len(sys.argv)
    if argcount == 1:
        show_usage()
        return False
    if argcount > 1:
        g_infile = sys.argv[1]
    if argcount > 2:
        g_outfile = sys.argv[2]

    return True

def perform_transform(xmldoc, xslproc, ods):
    result = xslproc.applyStylesheet(xmldoc, None)
    strval = xslproc.saveResultToString(result)

    ods.writestr("content.xml", strval, zipfile.ZIP_DEFLATED)

def transform_xmldoc_into_ods(xmldoc, ods):
    try:
        xsldoc = libxml2.readFile(g_transformxsl, None, 0)
        if xsldoc:
            try:
                xslproc = libxslt.parseStylesheetDoc(xsldoc)
                if xslproc:
                    try:
                        perform_transform(xmldoc, xslproc, ods)
                    except Exception as e:
                        sys.stderr.write("XSL Failed to transform (%s)." % e)
                    
                    xslproc.freeStylesheet()
                else:
                    sys.stderr.write("parseStylesheet failed to return a processor.")

            except libxml2.parserError as e:
                sys.stderr.write("Failed to parse XSL document \"transform.xsl\" (%s)." % e)
        else:
            sys.stderr.write("Failed to open XSL stylesheet %s." % g_transformxsl)
    except Exception as e:
        sys.stderr.write("libxml2 failed to read the stylesheet.")

def process_files(xmldoc, outfile):
    ods = zipfile.ZipFile(outfile,"w")
    if ods:
        ods.writestr("mimetype", mimetype, zipfile.ZIP_STORED)
        ods.writestr("META-INF/manifest.xml", META_dash_INF_manifest_xml, zipfile.ZIP_DEFLATED)
        ods.writestr("meta.xml", meta_xml, zipfile.ZIP_DEFLATED)
        ods.writestr("styles.xml", styles_xml, zipfile.ZIP_DEFLATED)
        transform_xmldoc_into_ods(xmldoc, ods)

        ods.close()

def get_outfile(xmldoc):
    global g_infile, g_outfile
    if g_outfile:
        outfile = open(g_outfile,"w")
        process_files(xmldoc, outfile)
        outfile.close()
    else:
        tfd, fpath = tempfile.mkstemp()
        if tfd:
            fs = os.fdopen(tfd, "w+")
            try:
                process_files(xmldoc, fs)
                fs.seek(0)
                os.write(1, fs.read())
            except Exception as e:
                sys.stderr.write("Error processing files (%s)." % e)

            fs.close()

def get_in_file():
    if g_infile:
        try:
            if g_infile == '-':
                fname = "stdout"
                xmldoc = libxml2.readFd(0, "input.xml", None, 0)
                
            else:
                fname = g_infile
                xmldoc = libxml2.readFile(g_infile, None, 0)
                
            get_outfile(xmldoc)
            xmldoc.freeDoc()
        except libxml2.parserError as e:
            sys.stderr.write("Failed to open XML document \"%s\" (%s)." % (fname, e))
    else:
        sys.stderr.write("No filename or '-' (for stdout) specified.")

def main():
    if set_global_filenames():
        get_in_file()

if __name__ == "__main__":
    main()
