class ez5.PdfCreator.Node.Body extends ez5.PdfCreator.Node

	__renderPdfContent: (opts) ->
		body = CUI.dom.$element("body")

		layoutData = @__getLayoutData()
		if not opts.preview and layoutData.outerBorder
			CUI.dom.addClass(body, "outer-border")

		if not @children or not opts.objects
			return body

		if layoutData.mode == "one_object"
			if opts.preview # In preview mode only one is rendered.
				@__renderObject(opts.objects[0], body, opts)
			else
				for object in opts.objects
					div = CUI.dom.div("pdf-break-page pdf-node-body-single")
					@__renderObject(object, div, opts)
					CUI.dom.append(body, div)
			return body

		chunkSize = layoutData.rows * layoutData.columns
		offset = 0
		while(opts.objects.length > offset)
			objects = opts.objects.slice(offset, offset + chunkSize)
			grid = @__renderPage(objects, opts)
			CUI.dom.append(body, grid)
			offset = offset + chunkSize

		return body

	__renderPage: (objects, opts) ->
		grid = CUI.dom.div("pdf-node-body-grid")
		CUI.dom.addClass(grid, "pdf-break-page")

		layoutData = @__getLayoutData()
		rowHeight = 100 / layoutData.rows
		columnWidth = 100 / layoutData.columns

		rowGap = layoutData.rowGap / 2
		columnGap = layoutData.columnGap / 2

		objectIndex = 0
		for rowIndex in [0...layoutData.rows]
			row = CUI.dom.div("pdf-node-body-row")
			CUI.dom.setStyle(row,
				height: "#{rowHeight}%"
			)

			if layoutData.innerBorder
				CUI.dom.addClass(row, "inner-border")

			for columnIndex in [0...layoutData.columns]
				column = CUI.dom.div("pdf-node-body-column")
				CUI.dom.append(row, column)
				CUI.dom.setStyle(column,
					width: "#{columnWidth}%"
					"padding": "#{rowGap}mm #{columnGap}mm #{rowGap}mm #{columnGap}mm"
				)
				if layoutData.innerBorder
					CUI.dom.addClass(column, "inner-border")

				div = CUI.dom.div("pdf-node-body-column-inner")
				@__renderObject(objects[objectIndex], div, opts)
				objectIndex++
				CUI.dom.append(column, div)

			CUI.dom.append(grid, row)

		return grid

	__renderObject: (object, container, opts) ->
		if not container
			return

		for node in @children
			contentOpts =
				object: object
				selectedNode: opts.selectedNode
				preview: opts.preview
				head: opts.head
			CUI.dom.append(container, node.renderPdfContent(contentOpts))
		return