//
// request_handler.cpp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2014 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include "request_handler.hpp"
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include "mime_types.hpp"
#include "reply.hpp"
#include "request.hpp"

#include "boost/algorithm/string.hpp"
#include "boost/property_tree/json_parser.hpp"
#include "../utf8utf16.h"
#include "../noun.h"
#include "../adjective.h"
#include "../verb.h"
#include "../other.h"
#include "../preposition.h"

namespace http {
	namespace server {

		request_handler::request_handler()
		{
		}

		void request_handler::handle_request(const request& req, reply& rep)
		{
			// Decode url to path.
			std::string request_path;
			if (!url_decode(req.uri, request_path))
			{
				rep = reply::stock_reply(reply::bad_request);
				return;
			}

			// Request path must be absolute and not contain "..".
			if (request_path.empty() || request_path[0] != '/'
				|| request_path.find("..") != std::wstring::npos)
			{
				rep = reply::stock_reply(reply::bad_request);
				return;
			}

			// If path ends in slash (i.e. is a directory) then add "index.html".
			if (request_path[request_path.size() - 1] == '/')
			{
				request_path += "index.html";
			}

			//Prepare request
			if (request_path[0] == '/')
			{
				request_path = std::string(request_path.begin() + 1, request_path.end());
			}

			boost::to_lower(request_path);

			
			std::wstring requestedStr = string_to_wstring(request_path);
			/*
			requestedStr = L"Вы запросили: " + requestedStr;

			rep.content = UTF16to8(requestedStr.c_str());

			rep.content = "<html><body>" + rep.content + "</body></html>";
			*/

			boost::property_tree::wptree propertyTree = PrepareReport(requestedStr);

			std::wstringstream output_stream;

			boost::property_tree::write_json(output_stream, propertyTree);

			std::string outputJsonCode = wstring_to_string(output_stream.str());

			rep.status = reply::ok;

			rep.content = outputJsonCode;

			rep.headers.resize(2);
			rep.headers[0].name = "Content-Length";
			rep.headers[0].value = std::to_string(rep.content.size());
			rep.headers[1].name = "Content-Type";
			rep.headers[1].value = "application/json; charset=utf-8";
		}

		bool request_handler::url_decode(const std::string& in, std::string& out)
		{

			out.clear();
			out.reserve(in.size());

			for (std::size_t i = 0; i < in.size(); ++i)
			{
				if (in[i] == '%')
				{
					if (i + 3 <= in.size())
					{
						int value = 0;
						std::istringstream is(in.substr(i + 1, 2));
						if (is >> std::hex >> value)
						{
							out += static_cast<char>(value);
							i += 2;
						}
						else
						{
							return false;
						}
					}
					else
					{
						return false;
					}
				}
				else if (in[i] == '+')
				{
					out += ' ';
				}
				else
				{
					out += in[i];
				}
			}


			return true;
		}


		boost::property_tree::wptree PrepareReport(std::wstring request)
		{
			boost::property_tree::wptree result;

			std::cout <<"PrepareReport" << std::endl;
			if (request.size() < 2)
			{
				result.put(L"error", L"String is too short");
			}


			int id;

			//Noun!

			std::set<NN::NounStruct> nounStructArr = NN::RecognizeNoun(request);

			id = 0;

			boost::property_tree::wptree wordArr;

			for (auto& nounStruct : nounStructArr)
			{
				boost::property_tree::wptree nounTree;

				nounTree.put(L"id", id);
				nounTree.put(L"word", "noun");
				nounTree.put(L"noun.grammaticalCase", NounGrammaticalCaseToWString(nounStruct.nounGrammaticalCase));
				nounTree.put(L"noun.animated", nounStruct.animated);
				nounTree.put(L"noun.count", NounCountToWString(nounStruct.nounCount));
				nounTree.put(L"noun.canBeAnimate", nounStruct.nounRecord.canBeAnimate);
				nounTree.put(L"noun.canBeInanimate", nounStruct.nounRecord.canBeInanimate);
				nounTree.put(L"noun.gender", nounStruct.nounRecord.gender);
				nounTree.put(L"noun.haveMultipleForm", nounStruct.nounRecord.haveMultipleForm);
				nounTree.put(L"noun.haveSingleForm", nounStruct.nounRecord.haveSingleForm);
				nounTree.put(L"noun.haveStandardMultipleForm", nounStruct.nounRecord.haveStandardMultipleForm);
				nounTree.put(L"noun.haveStandardMultipleFormWithMissingLastVowel", nounStruct.nounRecord.haveStandardMultipleFormWithMissingLastVowel);
				nounTree.put(L"noun.specialMultipleForm", nounStruct.nounRecord.specialMultipleForm);

				nounTree.put(L"noun.nominativeSingularForm", nounStruct.nounRecord.nominativeForm);

				boost::property_tree::wptree allTranslationsTree;

				for (auto& translationUnit : nounStruct.nounRecord.translationUnitArr)
				{
					boost::property_tree::wptree translationUnitTree;
					translationUnitTree.put(L"meaning", translationUnit.meaning);
					translationUnitTree.put(L"comment", translationUnit.comment);
					translationUnitTree.put(L"example", translationUnit.example);

					allTranslationsTree.push_back(std::make_pair(L"", translationUnitTree));
				}

				nounTree.put_child(L"translations", allTranslationsTree);

				wordArr.push_back(std::make_pair(L"", nounTree));
		
				id++;
			}

			//result.put_child(L"words", nounArr);

			//Adjective!

			std::set<AJ::AdjectiveStruct> adjectiveStructArr = AJ::RecognizeAdjective(request);

			//id = 0;


			for (auto& adjectiveStruct : adjectiveStructArr)
			{
				boost::property_tree::wptree adjectiveTree;

				adjectiveTree.put(L"id", id);
				adjectiveTree.put(L"word", "adjective");
				adjectiveTree.put(L"adjective.grammaticalCase", NounGrammaticalCaseToWString(adjectiveStruct.grammaticalCase));
				adjectiveTree.put(L"adjective.animated", adjectiveStruct.isDeclentionAnimated);
				adjectiveTree.put(L"adjective.count", NounCountToWString(adjectiveStruct.count));

				adjectiveTree.put(L"adjective.gender", adjectiveStruct.gender);
				
				adjectiveTree.put(L"adjective.nominativeSingularForm", adjectiveStruct.adjectiveRecord.nominativeMaleForm);

				boost::property_tree::wptree allTranslationsTree;

				for (auto& translationUnit : adjectiveStruct.adjectiveRecord.translationUnitArr)
				{
					boost::property_tree::wptree translationUnitTree;
					translationUnitTree.put(L"meaning", translationUnit.meaning);
					translationUnitTree.put(L"comment", translationUnit.comment);
					translationUnitTree.put(L"example", translationUnit.example);

					allTranslationsTree.push_back(std::make_pair(L"", translationUnitTree));
				}

				adjectiveTree.put_child(L"translations", allTranslationsTree);

				wordArr.push_back(std::make_pair(L"", adjectiveTree));

				id++;
			}

			
			std::set<VB::VerbStruct> verbStructArr = VB::RecognizeVerb(request);

			//id = 0;


			for (auto& verbStruct : verbStructArr)
			{
				boost::property_tree::wptree verbTree;

				
				verbTree.put(L"id", id);
				verbTree.put(L"word", "verb");

				verbTree.put(L"verb.infinitiveForm", verbStruct.verbRecord.infinitive);
				verbTree.put(L"verb.canBeImperfect", verbStruct.verbRecord.canBeImperfect);
				verbTree.put(L"verb.canBePerfect", verbStruct.verbRecord.canBePerfect);
				verbTree.put(L"verb.canBeNotPrefixed", verbStruct.verbRecord.canBeNotPrefixed);
				verbTree.put(L"verb.canBePrefixed", verbStruct.verbRecord.canBePrefixed);

				verbTree.put(L"verb.selfEnding", verbStruct.selfEnding);

				verbTree.put(L"verb.verbParams", VB::VerbParamsToWString(verbStruct.verbParams));

				boost::property_tree::wptree allTranslationsTree;

				for (auto& translationUnit : verbStruct.verbRecord.translationUnitArr)
				{
					boost::property_tree::wptree translationUnitTree;
					translationUnitTree.put(L"meaning", translationUnit.meaning);
					translationUnitTree.put(L"comment", translationUnit.comment);
					translationUnitTree.put(L"example", translationUnit.example);

					allTranslationsTree.push_back(std::make_pair(L"", translationUnitTree));
				}

				verbTree.put_child(L"translations", allTranslationsTree);


				wordArr.push_back(std::make_pair(L"", verbTree));

				id++;
			}

			std::set<OT::OtherWordRecord> otherWordStructArr = OT::RecognizeWord(request);

			//id = 0;


			for (auto& otherWordRecord : otherWordStructArr)
			{
				boost::property_tree::wptree otherWordTree;


				otherWordTree.put(L"id", id);
				otherWordTree.put(L"word", "otherWord");

				otherWordTree.put(L"otherWord.word", otherWordRecord.word);
				otherWordTree.put(L"otherWord.type", otherWordRecord.type);
				
				boost::property_tree::wptree allTranslationsTree;

				for (auto& translationUnit : otherWordRecord.translationUnitArr)
				{
					boost::property_tree::wptree translationUnitTree;
					translationUnitTree.put(L"meaning", translationUnit.meaning);
					translationUnitTree.put(L"comment", translationUnit.comment);
					translationUnitTree.put(L"example", translationUnit.example);

					allTranslationsTree.push_back(std::make_pair(L"", translationUnitTree));
				}

				otherWordTree.put_child(L"translations", allTranslationsTree);


				wordArr.push_back(std::make_pair(L"", otherWordTree));

				id++;
			}

			std::set<PP::PrepositionRecord> prepositionStructArr = PP::RecognizeWord(request);

			//id = 0;


			for (auto& prepositionStruct : prepositionStructArr)
			{
				boost::property_tree::wptree prepositionTree;


				prepositionTree.put(L"id", id);
				prepositionTree.put(L"word", "preposition");

				prepositionTree.put(L"preposition.infinitiveForm", prepositionStruct.word);
				prepositionTree.put(L"preposition.availableForGenitive", prepositionStruct.availableForGenitive);
				prepositionTree.put(L"preposition.availableForDative", prepositionStruct.availableForDative);
				prepositionTree.put(L"preposition.availableForAccusative", prepositionStruct.availableForAccusative);
				prepositionTree.put(L"preposition.availableForInstrumental", prepositionStruct.availableForInstrumental);
				prepositionTree.put(L"preposition.availableForPrepositional", prepositionStruct.availableForPrepositional);

				boost::property_tree::wptree allTranslationsTree;

				for (auto& translationUnit : prepositionStruct.translationUnitArr)
				{
					boost::property_tree::wptree translationUnitTree;
					translationUnitTree.put(L"meaning", translationUnit.meaning);
					translationUnitTree.put(L"comment", translationUnit.comment);
					translationUnitTree.put(L"example", translationUnit.example);

					allTranslationsTree.push_back(std::make_pair(L"", translationUnitTree));
				}

				prepositionTree.put_child(L"translations", allTranslationsTree);


				wordArr.push_back(std::make_pair(L"", prepositionTree));

				id++;
			}

			result.put_child(L"words", wordArr);



			return result;

		}
		
	} // namespace server
} // namespace http
