/**********************************************************************
 * LeechCraft - modular cross-platform feature rich internet client.
 * Copyright (C) 2006-2014  Georg Rudoy
 *
 * Boost Software License - Version 1.0 - August 17th, 2003
 *
 * Permission is hereby granted, free of charge, to any person or organization
 * obtaining a copy of the software and accompanying documentation covered by
 * this license (the "Software") to use, reproduce, display, distribute,
 * execute, and transmit the Software, and to prepare derivative works of the
 * Software, and to permit third-parties to whom the Software is furnished to
 * do so, all subject to the following:
 *
 * The copyright notices in the Software and this entire statement, including
 * the above license grant, this restriction and the following disclaimer,
 * must be included in all copies of the Software, in whole or in part, and
 * all derivative works of the Software, unless such copies or derivative
 * works are solely in the form of machine-executable object code generated by
 * a source language processor.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **********************************************************************/

#include "document.h"
#include "seen.h"
#include "docmanager.h"

namespace LeechCraft
{
namespace Monocle
{
namespace Seen
{
	namespace
	{
		static unsigned int FormatMask [4] = { 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 };
	}

	Document::Document (const QString& file, ddjvu_context_t *ctx, QObject *plugin, DocManager *mgr)
	: Context_ (ctx)
	, Doc_ (ddjvu_document_create_by_filename_utf8 (Context_, file.toUtf8 ().constData (), 1))
	, RenderFormat_ (ddjvu_format_create (DDJVU_FORMAT_RGBMASK32, 4, FormatMask))
	, DocMgr_ (mgr)
	, DocURL_ (QUrl::fromLocalFile (file))
	, Plugin_ (plugin)
	{
		ddjvu_format_set_row_order (RenderFormat_, 1);
		ddjvu_format_set_y_direction (RenderFormat_, 1);

		if (Doc_ && ddjvu_document_get_type (Doc_) != DDJVU_DOCTYPE_UNKNOWN)
			UpdateDocInfo ();
	}

	Document::~Document ()
	{
		ddjvu_format_release (RenderFormat_);
		DocMgr_->Unregister (Doc_);
		ddjvu_document_release (Doc_);
	}

	QObject* Document::GetBackendPlugin () const
	{
		return Plugin_;
	}

	QObject* Document::GetQObject ()
	{
		return this;
	}

	bool Document::IsValid () const
	{
		return Doc_;
	}

	DocumentInfo Document::GetDocumentInfo () const
	{
		return DocumentInfo ();
	}

	int Document::GetNumPages () const
	{
		return ddjvu_document_get_pagenum (Doc_);
	}

	QSize Document::GetPageSize (int pageNum) const
	{
		return Sizes_.value (pageNum);
	}

	QImage Document::RenderPage (int pageNum, double xScale, double yScale)
	{
		const auto& size = Sizes_.value (pageNum);

		QImage img (size, QImage::Format_RGB32);
		auto getScaled = [&img, xScale, yScale]
		{
			return img.scaled (img.width () * xScale, img.height () * yScale,
					Qt::KeepAspectRatio, Qt::SmoothTransformation);
		};

		if (std::max (xScale, yScale) < 0.01)
			return getScaled ();

		ddjvu_page_t *page = 0;
		if (PendingRenders_.contains (pageNum))
			page = PendingRenders_ [pageNum];
		else
		{
			page = ddjvu_page_create_by_pageno (Doc_, pageNum);
			PendingRenders_ [pageNum] = page;
			PendingRendersNums_ [page] = pageNum;
		}

		ddjvu_rect_s rect =
		{
			0,
			0,
			static_cast<unsigned int> (size.width ()),
			static_cast<unsigned int> (size.height ())
		};

		auto res = ddjvu_page_render (page,
				DDJVU_RENDER_COLOR,
				&rect,
				&rect,
				RenderFormat_,
				img.bytesPerLine (),
				reinterpret_cast<char*> (img.bits ()));
		qDebug () << Q_FUNC_INFO << pageNum << res;
		if (res)
		{
			PendingRenders_.remove (pageNum);
			PendingRendersNums_.remove (page);
			ddjvu_page_release (page);
		}

		return getScaled ();
	}

	QList<ILink_ptr> Document::GetPageLinks (int)
	{
		return QList<ILink_ptr> ();
	}

	QUrl Document::GetDocURL () const
	{
		return DocURL_;
	}

	ddjvu_document_t* Document::GetNativeDoc () const
	{
		return Doc_;
	}

	void Document::UpdateDocInfo ()
	{
		TryUpdateSizes ();
	}

	void Document::UpdatePageInfo (ddjvu_page_t*)
	{
		TryUpdateSizes ();
	}

	void Document::RedrawPage (ddjvu_page_t *page)
	{
		auto num = PendingRendersNums_ [page];
		emit pageContentsChanged (num);
	}

	void Document::TryUpdateSizes ()
	{
		const int numPages = GetNumPages ();
		for (int i = 0; i < numPages; ++i)
			if (!Sizes_.contains (i))
				TryGetPageInfo (i);
	}

	void Document::TryGetPageInfo (int pageNum)
	{
		ddjvu_pageinfo_t info;
		auto r = ddjvu_document_get_pageinfo (Doc_, pageNum, &info);
		if (r != DDJVU_JOB_OK)
			return;

		Sizes_ [pageNum] = QSize (info.width, info.height);
		emit pageSizeChanged (pageNum);
	}
}
}
}
