#include "doorkeeper/helpers/tylermapsource.hpp"
#include <limits>
#include <algorithm>
#include <ciso646>
#include <boost/lexical_cast.hpp>
#include <boost/utility/string_ref.hpp>
#include <iterator>

#if defined(__GNUC__)
#	include <endian.h>
#else
#	error "Unsupported compiler"
#endif
#include <algorithm>
#include <iterator>

//Vorbis comment specification: https://www.xiph.org/vorbis/doc/v-comment.html
//The comment header logically is a list of eight-bit-clean vectors; the number
//of vectors is bounded to 2^32-1 and the length of each vector is limited to
//2^32-1 bytes. The vector length is encoded; the vector contents themselves
//are not null terminated. In addition to the vector list, there is a single
//vector for vendor name (also 8 bit clean, length encoded in 32 bits). For
//example, the 1.0 release of libvorbis set the vendor string to "Xiph.Org
//libVorbis I 20020717".
//
//The comment header is decoded as follows:
//
//  1) [vendor_length] = read an unsigned integer of 32 bits
//  2) [vendor_string] = read a UTF-8 vector as [vendor_length] octets
//  3) [user_comment_list_length] = read an unsigned integer of 32 bits
//  4) iterate [user_comment_list_length] times {
//    5) [length] = read an unsigned integer of 32 bits
//    6) this iteration's user comment = read a UTF-8 vector as [length] octets
//  }

namespace dkh {
	namespace {
		typedef std::map<std::string, std::string> CommentMap;

		const uint32_t g_signature = 0x52504B44; //DKPR

		template <typename T> T lil_endian_to_machine ( T parIn ) a_pure;
		template<> uint64_t lil_endian_to_machine ( uint64_t parIn ) a_pure;
		template<> uint32_t lil_endian_to_machine ( uint32_t parIn ) a_pure;
		template<> uint16_t lil_endian_to_machine ( uint16_t parIn ) a_pure;
		template<> uint8_t lil_endian_to_machine ( uint8_t parIn ) a_pure;
		template<> implem::TylerMapHeader lil_endian_to_machine ( implem::TylerMapHeader parIn ) a_pure;
		template<> implem::TylerMapLayerHeader lil_endian_to_machine ( implem::TylerMapLayerHeader parIn ) a_pure;
#if defined(WITH_TYLERMAP_WRITER)
		template <typename T> T machine_to_lil_endian ( T parIn ) a_pure;
		template<> uint64_t machine_to_lil_endian ( uint64_t parIn ) a_pure;
		template<> uint32_t machine_to_lil_endian ( uint32_t parIn ) a_pure;
		template<> uint16_t machine_to_lil_endian ( uint16_t parIn ) a_pure;
		template<> uint8_t machine_to_lil_endian ( uint8_t parIn ) a_pure;
		template<> implem::TylerMapHeader machine_to_lil_endian ( implem::TylerMapHeader parIn ) a_pure;
		template<> implem::TylerMapLayerHeader machine_to_lil_endian ( implem::TylerMapLayerHeader parIn ) a_pure;
#endif

		template<> uint64_t lil_endian_to_machine (uint64_t parIn) { return le64toh(parIn); }
		template<> uint32_t lil_endian_to_machine (uint32_t parIn) { return le32toh(parIn); }
		template<> uint16_t lil_endian_to_machine (uint16_t parIn) { return le16toh(parIn); }
		template<> uint8_t lil_endian_to_machine (uint8_t parIn) { return parIn; }

		bool isdigit (char parChar) a_pure a_flatten;

		template<> implem::TylerMapHeader lil_endian_to_machine (implem::TylerMapHeader parIn) {
			parIn.signature = lil_endian_to_machine(parIn.signature);
			parIn.file_size = lil_endian_to_machine(parIn.file_size);
			parIn.version_major = lil_endian_to_machine(parIn.version_major);
			parIn.version_minor = lil_endian_to_machine(parIn.version_minor);
			parIn.layer_count = lil_endian_to_machine(parIn.layer_count);
			parIn.map_type = lil_endian_to_machine(parIn.map_type);
			parIn.hashing_algorithm = lil_endian_to_machine(parIn.hashing_algorithm);
			parIn.dimensions = lil_endian_to_machine(parIn.dimensions);
			parIn.dimensions_start = lil_endian_to_machine(parIn.dimensions_start);
			parIn.comment_start = lil_endian_to_machine(parIn.comment_start);
			parIn.layer_start = lil_endian_to_machine(parIn.layer_start);
			return parIn;
		}

		template<> implem::TylerMapLayerHeader lil_endian_to_machine (implem::TylerMapLayerHeader parIn) {
			parIn.layer_length = lil_endian_to_machine(parIn.layer_length);
			parIn.layer_format = lil_endian_to_machine(parIn.layer_format);
			return parIn;
		}

#if defined(WITH_TYLERMAP_WRITER)
		template<> uint64_t machine_to_lil_endian (uint64_t parIn) { return htole64(parIn); }
		template<> uint32_t machine_to_lil_endian (uint32_t parIn) { return htole32(parIn); }
		template<> uint16_t machine_to_lil_endian (uint16_t parIn) { return htole16(parIn); }
		template<> uint8_t machine_to_lil_endian (uint8_t parIn) { return parIn; }

		template<> implem::TylerMapHeader machine_to_lil_endian (implem::TylerMapHeader parIn) {
			parIn.signature = machine_to_lil_endian(parIn.signature);
			parIn.file_size = machine_to_lil_endian(parIn.file_size);
			parIn.version_major = machine_to_lil_endian(parIn.version_major);
			parIn.version_minor = machine_to_lil_endian(parIn.version_minor);
			parIn.layer_count = machine_to_lil_endian(parIn.layer_count);
			parIn.map_type = machine_to_lil_endian(parIn.map_type);
			parIn.hashing_algorithm = machine_to_lil_endian(parIn.hashing_algorithm);
			parIn.dimensions = machine_to_lil_endian(parIn.dimensions);
			parIn.dimensions_start = machine_to_lil_endian(parIn.dimensions_start);
			parIn.comment_start = machine_to_lil_endian(parIn.comment_start);
			parIn.layer_start = machine_to_lil_endian(parIn.layer_start);
			return parIn;
		}

		template<> implem::TylerMapLayerHeader machine_to_lil_endian (implem::TylerMapLayerHeader parIn) {
			parIn.layer_length = machine_to_lil_endian(parIn.layer_length);
			parIn.layer_format = machine_to_lil_endian(parIn.layer_format);
			return parIn;
		}
#endif

		template <typename T>
		T read_int (std::istream& parStream, T parMax=std::numeric_limits<T>::max()) {
			T retval;
			parStream.read(reinterpret_cast<char*>(&retval), sizeof(T));
			retval = lil_endian_to_machine(retval);

			if (retval > parMax)
				throw InvalidMapFileException();

			return retval;
		}

		std::string& read_string (std::istream& parStream, std::string& parString) {
			const uint32_t max_string_length = 1024 * 2;
			const uint32_t len = std::min(read_int<uint32_t>(parStream), max_string_length);
			std::istream_iterator<char> itstream(parStream);
			parString.resize(len);
			std::copy_n(itstream, len, std::insert_iterator<std::string>(parString, parString.begin()));
			return parString;
		}

#if defined(WITH_TYLERMAP_WRITER)
		template <typename T>
		void write_int (std::ostream& parStream, T parValue) {
			parValue = machine_to_lil_endian(parValue);
			parStream.write(reinterpret_cast<const char*>(&parValue), sizeof(T));
		}

		void write_string (std::ostream& parStream, const std::string& parString) {
			const uint32_t len = static_cast<uint32_t>(parString.size());
			write_int<uint32_t>(parStream, len);
			parStream.write(parString.c_str(), parString.size());
		}
#endif

		bool isdigit (char parChar) {
			return std::isdigit(parChar);
		}

		void read_comments (std::istream& parStream, std::string& parVendor, CommentMap& parComments) {
			//Technically there is no limit on strings other than the uint32
			//max value, but wth
			const uint32_t max_entries = 200;

			read_string(parStream, parVendor);
			const uint32_t list_length = read_int<uint32_t>(parStream, max_entries);
			std::string full_string;
			for (uint32_t z = 0; z < list_length; ++z) {
				read_string(parStream, full_string);
				auto equal_pos = full_string.find('=');
				if (std::string::npos == equal_pos)
					throw InvalidMapFileException();

				parComments[full_string.substr(0, equal_pos)] = full_string.substr(equal_pos + 1);
			}
		}

		void extract_array_from_comments (std::vector<std::string>& parOut, const std::string& parPrefix, const std::map<std::string, std::string>& parMap) {
			typedef decltype(std::distance(parPrefix.begin(), parPrefix.end())) diff_type;
			using std::size_t;
			using boost::lexical_cast;

			parOut.clear();
			for (const auto& itcurr : parMap) {
				const std::string& key = itcurr.first;
				if (parPrefix.size() + 3 > key.size())
					continue;

				if (not std::equal(parPrefix.begin(), parPrefix.end(), key.begin()))
					continue;

				if (key[parPrefix.size()] != '[')
					continue;

				auto it_past_index = std::find_if_not(key.begin() + parPrefix.size() + 1, key.end(), &isdigit);
				if (it_past_index == key.end())
					continue;
				if (*it_past_index != ']')
					continue;

				if (std::distance(key.begin(), it_past_index) + 1 != static_cast<diff_type>(key.size()))
					continue;

				boost::string_ref index_part(key);
				const auto dist = std::distance(key.begin(), it_past_index);
				DK_ASSERT(dist > static_cast<diff_type>(parPrefix.size() + 1));
				index_part = index_part.substr(parPrefix.size() + 1, dist - parPrefix.size() - 1);
				const size_t index = lexical_cast<size_t>(index_part);
				if (index >= parMap.size())
					continue;

				if (parOut.size() <= index)
					parOut.resize(index + 1);
				parOut[index] = itcurr.second;
			}
		}
	} //unnamed namespace

	namespace implem {
		struct TylerMapSourceBase::LayerInfo {
			dk::HashType hash;
			uint32_t data_start;
			uint32_t data_length;
		};

		TylerMapSourceBase::TylerMapSourceBase (pos_type parStreamStartPos) :
			m_stream_start(parStreamStartPos)
		{
		}

		TylerMapSourceBase::~TylerMapSourceBase() {
		}

		dk::HashType TylerMapSourceBase::layerTypeHash (int parIndex) const {
			DK_ASSERT(parIndex >= 0);
			DK_ASSERT(static_cast<std::size_t>(parIndex) < m_layers_info.size());
			return m_layers_info[parIndex].hash;
		}

		void TylerMapSourceBase::chainedMaps (std::vector<std::string>& parOut) const {
			extract_array_from_comments(parOut, "chained_map", m_comments);
		}

		dk::MapTypes TylerMapSourceBase::mapType() const {
			return m_map_type;
		}

		void TylerMapSourceBase::parseMapHeaders (std::istream& parSrc, uint32_t parDim, std::vector<uint32_t>& parMapDims, std::vector<uint16_t>& parTileDims) {
			//Read file header
			implem::TylerMapHeader header;
			implem::read_header(parSrc, header);

			if (header.dimensions != parDim) {
				throw InvalidMapDimensionsException();
			}

			switch (header.map_type) {
			case dk::MapType_IsometricStaggered:
				m_map_type = dk::MapType_IsometricStaggered;
				break;
			case dk::MapType_Isometric:
				m_map_type = dk::MapType_Isometric;
				break;
			case dk::MapType_Orthogonal:
				m_map_type = dk::MapType_Orthogonal;
				break;
			case dk::MapType_Hex:
				m_map_type = dk::MapType_Hex;
				break;
			default:
				throw InvalidMapFileException();
			}

			//Read map and tile dimensions
			{
				std::vector<uint32_t> map_dims;
				std::vector<uint16_t> tile_dims;
				const auto read_start = (header.dimensions_start > sizeof(header) ? header.dimensions_start - sizeof(header) : sizeof(header));
				parSrc.seekg(read_start, std::ios_base::cur);
				implem::read_dimensions(parSrc, parDim, map_dims, tile_dims);
				parMapDims.swap(map_dims);
				parTileDims.swap(tile_dims);
			}

			//Read vorbis comments
			parSrc.seekg(header.comment_start + m_stream_start, std::ios_base::beg);
			read_comments(parSrc, m_file_vendor, m_comments);
		}

		void read_header (std::istream& parStream, TylerMapHeader& parHeader) {
			parStream.read(reinterpret_cast<char*>(&parHeader), sizeof(TylerMapHeader));
			parHeader = lil_endian_to_machine(parHeader);

			if (g_signature != parHeader.signature)
				throw InvalidMapFileException();
		}

		void read_layer_header (std::istream& parStream, TylerMapLayerHeader& parHeader) {
			parStream.read(reinterpret_cast<char*>(&parHeader), sizeof(TylerMapLayerHeader));
			parHeader = lil_endian_to_machine(parHeader);
		}

		void read_dimensions (std::istream& parStream, uint32_t parDimensions, std::vector<uint32_t>& parMap, std::vector<uint16_t>& parTile) {
			parMap.reserve(parMap.size() + parDimensions);
			for (uint32_t z = 0; z < parDimensions; ++z) {
				const auto dim = read_int<uint32_t>(parStream);
				parMap.push_back(dim);
			}

			parTile.reserve(parTile.size() + parDimensions);
			for (uint32_t z = 0; z < parDimensions; ++z) {
				const auto dim = read_int<uint16_t>(parStream);
				parTile.push_back(dim);
			}
		}
	} //namespace implem
} //namespace dkh
