import importlib

from openpack.basepack import ContentType
from openpack.officepack import OfficePackage

from . import document


def initialize():
	"""
	Import various modules so their Part classes are present.
	"""
	for mod in 'document numbering styles headerfooter'.split():
		importlib.import_module('paradocx.' + mod)


initialize()


class WordPackage(OfficePackage):
	def __init__(self):
		"""
		Construct a WordPackage.
		"""
		super(WordPackage, self).__init__()
		self.quickstart()

	def _load(self, *args, **kwargs):
		# re-initialize this package without the quickstart
		super(WordPackage, self).__init__()
		super(WordPackage, self)._load(*args, **kwargs)

	def quickstart(self):
		self.content_types.add(
			ContentType.Default(
				"application/xml",
				"xml",
			)
		)
		self.content_types.add(
			ContentType.Default(
				"application/vnd.openxmlformats-package.relationships+xml",
				"rels",
			)
		)
		start = document.DocumentPart(self, '/word/document.xml')
		self.content_types.add(
			ContentType.Override(
				start.content_type,
				start.name,
			)
		)
		self[start.name] = start
		self.relate(start)


if __name__ == '__main__':
	import sys
	from textwrap import dedent
	from this import s as zen_encoded
	from openpack.basepack import CoreProperties

	trun = dedent("""
		<w:p>
			<w:r>
				<w:t>%s</w:t>
			</w:r>
		</w:p>
		""").lstrip()
	raw_zen = zen_encoded.decode('rot13')
	zen = "".join(trun % line for line in raw_zen.splitlines())

	body = dedent("""
		<?xml version="1.0" encoding="utf-8"?>
		<w:document
		xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
			<w:body>
				<w:p>
					<w:r><w:t>Generated by:</w:t></w:r>
				</w:p>
				<w:p>
					<w:r><w:t>Python %s</w:t></w:r>
				</w:p>
				%s
			</w:body>
		</w:document>
		""").lstrip() % (sys.version, zen)
	op = WordPackage()
	op.start_part.data = body.decode('utf-8')
	cp = CoreProperties(op, '/docProps/core.xml')
	cp.encoding = 'utf-8'
	op.add(cp)
	op.relate(cp)
	cp.creator = "Testy McTest"
	op.save('test.docx')
