#!/usr/bin/env python

import getopt, sys, os, glob, time, subprocess, uno, unohelper

from com.sun.star.beans import PropertyValue
from com.sun.star.connection import NoConnectException
from com.sun.star.io import IOException, XOutputStream
from com.sun.star.script import CannotConvertException
from com.sun.star.uno import Exception as UnoException

# an output sink ...
class OutputStream(unohelper.Base, XOutputStream):
  def __init__(self):
    self.closed = 0
  def closeOutput(self):
    self.closed = 1
  def writeBytes(self, seq):
    sys.stdout.write(seq.value)
  def flush(self):
    pass

cmpt_ctxt = uno.getComponentContext()
resolver = cmpt_ctxt.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", cmpt_ctxt)
oopid = None

ifn = sys.argv[1]

connection = "socket,host=localhost,port=2002;urp;StarOffice.ComponentContext"
try:
  ctxt = resolver.resolve("uno:%s" % op.connection)
except:
  try:
    oopid = subprocess.Popen(["ooffice", "-nologo", "-nodefault", "-accept=%s" % connection]).pid
    time.sleep(1)
    ctxt = resolver.resolve("uno:%s" % connection)
  except:
    print "Failed to connect to existing OpenOffice instance or create a new one"
    exit(1)

service_mgr = ctxt.ServiceManager
desktop = service_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctxt)
cwd = unohelper.systemPathToFileUrl(os.getcwd())

doc = desktop.loadComponentFromURL(
  unohelper.absolutize(cwd, unohelper.systemPathToFileUrl(ifn)), "_blank", 0,
  (PropertyValue( "Hidden" , 0 , True, 0 ),))


(bifn, ext) = os.path.splitext(ifn)
for i in range(0, doc.getDrawPages().getCount()):
  curp = doc.getDrawPages().getByIndex(i)
  # 21*px
  curp.Width = 15512
  curp.Height = 10080
  doc.getCurrentController().setCurrentPage(curp)
  ofn = "%s_%03d.png" % (bifn, i)
  doc.storeToURL(unohelper.absolutize(cwd, unohelper.systemPathToFileUrl(ofn)),
    (PropertyValue("FilterName", 0, "impress_png_Export", 0),
     PropertyValue("Overwrite", 0, True, 0),
     PropertyValue( "OutputStream", 0, OutputStream(), 0)))
