#!/usr/bin/env python
import os
import cgi
from lxml import etree
import cgitb
cgitb.enable()  # This line enables CGI error reporting
import sys
import json
import traceback
import jinja2
from configuration import Configuration
from os.path import expanduser

def CreateSynfigGeometry(Width, Height):
    SynfigUnit = 60.0
    synfigWidth = 480 / SynfigUnit
    synfigHeight = 270 / SynfigUnit
    Resolution = 72.0

    LHViewboxWidth = "{0:.6f}".format(0 - synfigWidth / 2)
    TOPViewboxHeight = "{0:.6f}".format(synfigHeight / 2)
    RHViewboxWidth = "{0:.6f}".format(synfigWidth / 2)
    BOTTOMViewboxHeight = "{0:.6f}".format(0 - synfigHeight / 2)

    xres = 39.3700798889 * Resolution

    view_box =  str(LHViewboxWidth) + " " + str(TOPViewboxHeight) \
    + " " + str(RHViewboxWidth) + " " + str(BOTTOMViewboxHeight)

    sys.stderr.write(view_box)

    sys.stderr.write("\n")

    result = {
        'width': Width,
        'height': Height,
        'xres': "{0:.6f}".format(xres),
        'yres': "{0:.6f}".format(xres),
        'view-box': view_box}
    return result

def saveFileContent(filename, value):
        mypath = os.path.join(os.getcwd(), "OEBPS/Text/" + filename)
        f = open(mypath, 'w')
        f.write(value)
        f.close()


try:
    PROJECT_LOCATION = os.getcwd()
    result = {}
    cgitb.enable()
    form = cgi.FieldStorage()
    d = {}

    for k in form.keys():
        d[k] = form.getvalue(k)
#    result['data'] = d
    cast = form.getvalue("Cast[]")
    PROJECT_LOCATION = os.getcwd()
    TEMP_FOLDER = os.path.join(os.getcwd(), 'temp')
    TEMPLATE_FILE = "synfig-scene-template.sif"
    print "Content-type: application/json"
    print
    templateLoader = jinja2.FileSystemLoader(searchpath=PROJECT_LOCATION)
    templateEnv = jinja2.Environment(loader=templateLoader)
    template = templateEnv.get_template(TEMPLATE_FILE)
    Width=form.getvalue('Width')
    Height=form.getvalue('Height')
    FPS = form.getvalue('FPS')
    TITLE = form.getvalue('title')
    #TODO : pull this back from the passed in json object.
    Geometry = CreateSynfigGeometry(Width, Height)
    sys.stderr.write(Geometry['view-box'])
    sys.stderr.write("\n")

    templateVars = {
        "TITLE": TITLE,
        "WIDTH": Width,
        "HEIGHT": Height,
        "FPS": FPS,
        "XRES": Geometry['xres'],
        "YRES": Geometry['yres'],
        "VIEWBOX": Geometry['view-box']


         }
    files = form.getvalue("Cast[]")
    #Create  TEMP_FOLDER = os.path.join(os.getcwd(), 'temp')
    import uuid
    unique_filename = str(uuid.uuid4())
    outputText = template.render(templateVars)
    result['success'] = True
    result['message'] = "The command Completed Successfully"
    result['filecontent'] = outputText
    result['file']=unique_filename

    #tree = etree.XML(outputText)
    parser = etree.XMLParser(recover=True)
    tree = etree.fromstring(outputText, parser)

    tree = etree.ElementTree(tree)
    parser = etree.XMLParser(remove_blank_text=False)

    path = os.path.join(PROJECT_LOCATION,'synfig-scene-builder.config')
    c = Configuration(path)
    castfolder = expanduser(c.Cast_Location())




    for file in files:
        fixedFile =''
        if file.strip().startswith('/'):
            fixedFile = file.strip()[1:]

        queen = etree.parse(os.path.join(castfolder.strip(), fixedFile.strip()))
        queen_canvases = queen.xpath('/canvas/defs/canvas')
        tree_canvases = tree.xpath('/canvas/defs')

        if len(tree_canvases) == 0:
            root = tree.xpath('/canvas')[0]
            defs = etree.SubElement(root, "defs")
            tree_canvases = tree.xpath('/canvas/defs')
            #Append the canvases
        for canvas in queen_canvases:
                addingCanvas = canvas.get("id")
                count = len(tree.xpath('/canvas/defs/canvas[@id="'+addingCanvas+'"]'))
                if count == 0 :
                    tree_canvases[0].append(canvas)
                    count2 = len(tree.xpath('/canvas/defs/canvas[@id="'+addingCanvas+'"]'))
                else:
                    pass
        #append the layers
        #    pass
        tree_layers = tree.xpath('/canvas')[0]
        queen_layers = queen.xpath('/canvas/layer')
        for queen_layer in queen_layers:
            addingLayer = queen_layer.get("desc")
            if addingLayer is None :
                addingLayer = "Undefined_Layer_Name"
            count = len(tree.xpath('/canvas/layer[starts-with(@desc,"' + str(addingLayer) + '")]'))
            if addingLayer is not None and  count >0:
                queen_layer.set("desc",addingLayer + "_" + str(count))
            tree_layers.append(queen_layer)
    value = etree.tostring(tree,pretty_print=True)
    #send the output
    mypath = os.path.join(TEMP_FOLDER,unique_filename)
    f = open( mypath, 'w' )
    f.write(value )
    f.close()
    result['file']=str(unique_filename)
    result['filecontent'] = "read the file"
except Exception as e:
        result['success'] = False
        result['message'] = "The command failed :" + str(e)
        result['detail'] = e.message
        traceback.print_exc(file=sys.stderr)
finally:
        print(json.JSONEncoder().encode(result))



