/**********************************************************************
 * 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 "docstatemanager.h"
#include <boost/version.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <util/util.h>
#include <util/sys/paths.h>
#include "common.h"

#if BOOST_VERSION >= 105000
#define SANE_JSON
#endif

#ifndef SANE_JSON
#pragma warning("Boost 1.50 or higher is NOT available, state management will not work.")
#endif

namespace LeechCraft
{
namespace Monocle
{
	namespace
	{
		QString GetFileName (const QString& id)
		{
			return id.at (0) + '/' + id + ".json";
		}
	}

	DocStateManager::DocStateManager (QObject *parent)
	: QObject (parent)
	, DocDir_ (Util::CreateIfNotExists ("monocle/docstate"))
	{
	}

	namespace bp = boost::property_tree;

	void DocStateManager::SetState (const QString& id, const State& state)
	{
#ifdef SANE_JSON
		const auto& filename = DocDir_.absoluteFilePath (GetFileName (id));
		if (!DocDir_.exists (id.at (0)))
			DocDir_.mkdir (id.at (0));

		bp::ptree pt;
		pt.put ("page", state.CurrentPage_);
		pt.put ("scale", state.CurrentScale_);
		pt.put ("layout", state.Lay_ == LayoutMode::OnePage ? "one" : "two");

		std::string scaleModeStr;
		switch (state.ScaleMode_)
		{
		case ScaleMode::FitWidth:
			scaleModeStr = "fitWidth";
			break;
		case ScaleMode::FitPage:
			scaleModeStr = "fitPage";
			break;
		case ScaleMode::Fixed:
			scaleModeStr = "fixed";
			break;
		}
		pt.put ("scaleMode", scaleModeStr);

		bp::write_json (filename.toUtf8 ().constData (), pt);
#endif
	}

	auto DocStateManager::GetState (const QString& id) const -> State
	{
		State result = { 0, LayoutMode::OnePage, -1, ScaleMode::FitWidth };
#ifdef SANE_JSON
		const auto& filename = DocDir_.absoluteFilePath (GetFileName (id));
		if (!QFile::exists (filename))
			return result;

		bp::ptree pt;
		try
		{
			bp::read_json (filename.toUtf8 ().constData (), pt);
		}
		catch (const std::exception& e)
		{
			qWarning () << Q_FUNC_INFO
					<< "error reading"
					<< filename
					<< e.what ();
			return result;
		}

		if (auto page = pt.get_optional<int> ("page"))
			result.CurrentPage_ = *page;
		if (auto scale = pt.get_optional<double> ("scale"))
			result.CurrentScale_ = *scale;
		if (auto layout = pt.get_optional<std::string> ("layout"))
			result.Lay_ = *layout == "one" ? LayoutMode::OnePage : LayoutMode::TwoPages;
		if (auto scaleMode = pt.get_optional<std::string> ("scaleMode"))
		{
			if (*scaleMode == "fitWidth")
				result.ScaleMode_ = ScaleMode::FitWidth;
			else if (*scaleMode == "fitPage")
				result.ScaleMode_ = ScaleMode::FitPage;
			else
				result.ScaleMode_ = ScaleMode::Fixed;
		}
#endif
		return result;
	}
}
}
