// Copyright (c) 2012, Thomas Goyne <plorkyeran@aegisub.org>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

/// @file charset_6937.cpp
/// @brief A charset converter for ISO-6937-2
/// @ingroup libaegisub

#include "charset_6937.h"

#include <cerrno>
#include <iconv.h>

#include <boost/range/algorithm/lower_bound.hpp>

namespace {

// ISO-6937-2 values for the first 383 codepoints
const int iso6937_codepoints[] = {
	0x00,   0x01,   0x02,   0x03,   0x04,
	0x05,   0x06,   0x07,   0x08,   0x09,
	0x0A,   0x0B,   0x0C,   0x0D,   0x0E,
	0x0F,   0x10,   0x11,   0x12,   0x13,
	0x14,   0x15,   0x16,   0x17,   0x18,
	0x19,   0x1A,   0x1B,   0x1C,   0x1D,
	0x1E,   0x1F,   0x20,   0x21,   0x22,
	0x23,   0x24,   0x25,   0x26,   0x27,
	0x28,   0x29,   0x2A,   0x2B,   0x2C,
	0x2D,   0x2E,   0x2F,   0x30,   0x31,
	0x32,   0x33,   0x34,   0x35,   0x36,
	0x37,   0x38,   0x39,   0x3A,   0x3B,
	0x3C,   0x3D,   0x3E,   0x3F,   0x40,
	0x41,   0x42,   0x43,   0x44,   0x45,
	0x46,   0x47,   0x48,   0x49,   0x4A,
	0x4B,   0x4C,   0x4D,   0x4E,   0x4F,
	0x50,   0x51,   0x52,   0x53,   0x54,
	0x55,   0x56,   0x57,   0x58,   0x59,
	0x5A,   0x5B,   0x5C,   0x5D,   0x5E,
	0x5F,   0x60,   0x61,   0x62,   0x63,
	0x64,   0x65,   0x66,   0x67,   0x68,
	0x69,   0x6A,   0x6B,   0x6C,   0x6D,
	0x6E,   0x6F,   0x70,   0x71,   0x72,
	0x73,   0x74,   0x75,   0x76,   0x77,
	0x78,   0x79,   0x7A,   0x7B,   0x7C,
	0x7D,   0x7E,   0x7F,   0x80,   0x81,
	0x82,   0x83,   0x84,   0x85,   0x86,
	0x87,   0x88,   0x89,   0x8A,   0x8B,
	0x8C,   0x8D,   0x8E,   0x8F,   0x90,
	0x91,   0x92,   0x93,   0x94,   0x95,
	0x96,   0x97,   0x98,   0x99,   0x9A,
	0x9B,   0x9C,   0x9D,   0x9E,   0x9F,
	0xA0,   0xA1,   0xA2,   0xA3,   0xA8,
	0xA5,   0x00,   0xA7,   0xC820, 0xD3,
	0xE3,   0xAB,   0x00,   0x00,   0xD2,
	0xC520, 0xB0,   0xB1,   0xB2,   0xB3,
	0xC220, 0xB5,   0xB6,   0xB7,   0xCB20,
	0xD1,   0xEB,   0xBB,   0xBC,   0xBD,
	0xBE,   0xBF,   0xC141, 0xC241, 0xC341,
	0xC441, 0xC841, 0xCA41, 0xE1,   0xCB43,
	0xC145, 0xC245, 0xC345, 0xC845, 0xC149,
	0xC249, 0xC349, 0xC849, 0xE2,   0xC44E,
	0xC14F, 0xC24F, 0xC34F, 0xC44F, 0xC84F,
	0xB4,   0xE9,   0xC155, 0xC255, 0xC355,
	0xC855, 0xC259, 0xEC,   0xFB,   0xC161,
	0xC261, 0xC361, 0xC461, 0xC861, 0xCA61,
	0xF1,   0xCB63, 0xC165, 0xC265, 0xC365,
	0xC865, 0xC169, 0xC269, 0xC369, 0xC869,
	0xF3,   0xC46E, 0xC16F, 0xC26F, 0xC36F,
	0xC46F, 0xC86F, 0xB8,   0xF9,   0xC175,
	0xC275, 0xC375, 0xC875, 0xC279, 0xFC,
	0xC879, 0xC541, 0xC561, 0xC641, 0xC661,
	0xCE41, 0xCE61, 0xC243, 0xC263, 0xC343,
	0xC363, 0xC743, 0xC763, 0xCF43, 0xCF63,
	0xCF44, 0xCF64, 0x00,   0xF2,   0xC545,
	0xC565, 0x00,   0x00,   0xC745, 0xC765,
	0xCE45, 0xCE65, 0xCF45, 0xCF65, 0xC347,
	0xC367, 0xC647, 0xC667, 0xC747, 0xC767,
	0xCB47, 0xCB67, 0xC348, 0xC368, 0xE4,
	0xF4,   0xC449, 0xC469, 0xC549, 0xC569,
	0x00,   0x00,   0xCE49, 0xCE69, 0xC749,
	0xF5,   0xE6,   0xF6,   0xC34A, 0xC36A,
	0xCB4B, 0xCB6B, 0xF0,   0xC24C, 0xC26C,
	0xCB4C, 0xCB6C, 0xCF4C, 0xCF6C, 0xE7,
	0xF7,   0xE8,   0xF8,   0xC24E, 0xC26E,
	0xCB4E, 0xCB6E, 0xCF4E, 0xCF6E, 0xEF,
	0xEE,   0xFE,   0xC54F, 0xC56F, 0x00,
	0x00,   0xCD4F, 0xCD6F, 0xEA,   0xFA,
	0xC252, 0xC272, 0xCB52, 0xCB72, 0xCF52,
	0xCF72, 0xC253, 0xC273, 0xC353, 0xC373,
	0xCB53, 0xCB73, 0xCF53, 0xCF73, 0xCB54,
	0xCB74, 0xCF54, 0xCF74, 0xED,   0xFD,
	0xC455, 0xC475, 0xC555, 0xC575, 0xC655,
	0xC675, 0xCA55, 0xCA75, 0xCD55, 0xCD75,
	0xCE55, 0xCE75, 0xC357, 0xC377, 0xC359,
	0xC379, 0xC859, 0xC25A, 0xC27A, 0xC75A,
	0xC77A, 0xCF5A, 0xCF7A
};

struct extended_range {
	const int codepoint;
	const int value;
};

#ifdef _MSC_VER
// Needed for msvc's debug assertions
bool operator<(extended_range const& lft, extended_range const& rgt) {
	return lft.codepoint < rgt.codepoint;
}

bool operator<(int lft, extended_range const& rgt) {
	return lft < rgt.codepoint;
}
#endif

bool operator<(extended_range const& lft, int rgt) {
	return lft.codepoint < rgt;
}

// ISO-6937-2 values for codepoints that don't come in a nice contiguous block
const extended_range iso6937_extended_codepoints[] = {
	{ 0x02C7, 0xCF20 },
	{ 0x02D8, 0xC620 },
	{ 0x02D9, 0xC720 },
	{ 0x02DA, 0xCA20 },
	{ 0x02DB, 0xCE20 },
	{ 0x02DD, 0xCD20 },
	{ 0x2014, 0xD0 },
	{ 0x2018, 0xA9 },
	{ 0x2019, 0xB9 },
	{ 0x201C, 0xAA },
	{ 0x201D, 0xBA },
	{ 0x2022, 0xD4 },
	{ 0x20AC, 0xA4 }, // ETSI EN 300 468 extension: euro sign at A4
	{ 0x2126, 0xE0 },
	{ 0x215B, 0xDC },
	{ 0x215C, 0xDD },
	{ 0x215D, 0xDE },
	{ 0x2190, 0xAC },
	{ 0x2191, 0xAD },
	{ 0x2192, 0xAE },
	{ 0x2193, 0xAF },
	{ 0x266A, 0xD5 }
};

/// Get the ISO-6937-2 value for the given unicode codepoint or 0 if it cannot be mapped
int get_iso6937(int codepoint) {
	if (static_cast<size_t>(codepoint) < std::size(iso6937_codepoints))
		return iso6937_codepoints[codepoint];

	auto ext = boost::lower_bound(iso6937_extended_codepoints, codepoint);
	if (ext == std::end(iso6937_extended_codepoints) || ext->codepoint != codepoint)
		return 0;
	return ext->value;
}

} // namespace {

namespace agi::charset {

#ifdef _LIBICONV_VERSION
#define INTERNAL_CHARSET "UCS-4-INTERNAL"
#else
#define INTERNAL_CHARSET "WCHAR_T"
#endif

Converter6937::Converter6937(bool subst, const char *src)
: to_ucs4(Converter::create(true, src, INTERNAL_CHARSET))
, subst(subst)
{
}

size_t Converter6937::Convert(const char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft) {
	// No state to reset
	if (!inbuf || !inbytesleft)
		return 0;

	size_t bytes_written = 0;

	while (*inbytesleft > 0) {
		int in_val = 0;

		// Copy inbuf/inbytesleft so that we don't update them if the
		// conversion fails (due to not enough space or a bad sequence)
		const char *inbuftmp = *inbuf;
		size_t inbyteslefttmp = *inbytesleft;

		char *val_buf = reinterpret_cast<char *>(&in_val);
		size_t val_buf_size = sizeof(in_val);

		// Get the next unicode character from the input
		size_t ret = to_ucs4->Convert(&inbuftmp, &inbyteslefttmp, &val_buf, &val_buf_size);
		if (ret == (size_t)-1 && errno != E2BIG)
			return ret;

		// And convert that to ISO-6937-2
		int val = get_iso6937(in_val);
		if (!val && in_val) {
			if (subst) {
				val = '?';
			}
			else {
				errno = EILSEQ;
				return (size_t)-1;
			}
		}

		if (*outbytesleft < 1 || (val > 255 && *outbytesleft < 2)) {
			errno = E2BIG;
			return (size_t)-1;
		}

#define WRITE_BYTE(b) \
		do { \
			*(*outbuf)++ = (b); \
			--*outbytesleft; \
			++bytes_written; \
		} while(0)

		if (val <= 255)
			WRITE_BYTE(val);
		else {
			WRITE_BYTE((val >> 8) & 0xFF);
			WRITE_BYTE(val & 0xFF);
		}

		// Update the input pointers now that the conversion has succeeded
		*inbuf = inbuftmp;
		*inbytesleft = inbyteslefttmp;
	}

	return bytes_written;
}

} // namespace agi::charset
