/*
   +----------------------------------------------------------------------+
   | Copyright © The PHP Group and Contributors.                          |
   +----------------------------------------------------------------------+
   | This source file is subject to the Modified BSD License that is      |
   | bundled with this package in the file LICENSE, and is available      |
   | through the World Wide Web at <https://www.php.net/license/>.        |
   |                                                                      |
   | SPDX-License-Identifier: BSD-3-Clause                                |
   +----------------------------------------------------------------------+
   | Authors: Stanislav Malyshev <stas@zend.com>                          |
   +----------------------------------------------------------------------+
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <unicode/fmtable.h>
#include <unicode/curramt.h>
#include <unicode/ustring.h>
#include "../intl_convertcpp.h"
#include "formatter_class.h"
#include "formatter_format.h"

extern "C" {
#include "php_intl.h"
}

#include <locale.h>
#include <memory>

#define ICU_LOCALE_BUG 1

static bool numfmt_utf8_offset_to_utf16(const char *str, size_t str_len, int32_t *position, UErrorCode *status)
{
	int32_t utf16_position;

	if (*position < 0 || (size_t) *position > str_len) {
		return true;
	}

	*status = U_ZERO_ERROR;
	u_strFromUTF8(nullptr, 0, &utf16_position, str, *position, status);
	if (*status != U_BUFFER_OVERFLOW_ERROR && U_FAILURE(*status)) {
		return false;
	}
	*status = U_ZERO_ERROR;

	*position = utf16_position;
	return true;
}

static int32_t numfmt_utf16_offset_to_utf8(const icu::UnicodeString &str, int32_t position)
{
	int32_t utf8_position;
	UErrorCode status = U_ZERO_ERROR;

	if (position < 0 || position > str.length()) {
		return position;
	}

	u_strToUTF8(nullptr, 0, &utf8_position, str.getBuffer(), position, &status);
	if (status != U_BUFFER_OVERFLOW_ERROR && U_FAILURE(status)) {
		return position;
	}

	return utf8_position;
}

/* {{{ Parse a number. */
U_CFUNC PHP_FUNCTION( numfmt_parse )
{
	zend_long type = FORMAT_TYPE_DOUBLE;
	char* str = NULL;
	size_t str_len;
	int32_t position = 0;
	zval *zposition = NULL;
	char *oldlocale;
	FORMATTER_METHOD_INIT_VARS;

	/* Parse parameters. */
	if (zend_parse_method_parameters( ZEND_NUM_ARGS(), getThis(), "Os|lz!",
		&object, NumberFormatter_ce_ptr,  &str, &str_len, &type, &zposition ) == FAILURE )
	{
		RETURN_THROWS();
	}

	if (zposition) {
		zend_long long_position = zval_get_long(zposition);
		if (UNEXPECTED(long_position < INT32_MIN || long_position > INT32_MAX)) {
			zend_argument_value_error(hasThis() ? 3 : 4, "must be between %d and %d", INT32_MIN, INT32_MAX);
			RETURN_THROWS();
		}
		position = (int32_t) long_position;
	}

	/* Fetch the object. */
	FORMATTER_METHOD_FETCH_OBJECT;

	/* Convert given string to UTF-16. */
	icu::UnicodeString ustr;
	intl_stringFromChar(ustr, str, str_len, &INTL_DATA_ERROR_CODE(nfo));
	INTL_METHOD_CHECK_STATUS( nfo, "String conversion to UTF-16 failed" );
	if (zposition && !numfmt_utf8_offset_to_utf16(str, str_len, &position, &INTL_DATA_ERROR_CODE(nfo))) {
		INTL_METHOD_CHECK_STATUS(nfo, "Invalid UTF-8 offset");
	}

#if ICU_LOCALE_BUG && defined(LC_NUMERIC)
	/* need to copy here since setlocale may change it later */
	oldlocale = estrdup(setlocale(LC_NUMERIC, NULL));
	setlocale(LC_NUMERIC, "C");
#endif

	switch(type) {
		case FORMAT_TYPE_INT32:
		case FORMAT_TYPE_INT64:
		case FORMAT_TYPE_DOUBLE:
		{
			icu::Formattable result;
			icu::ParsePosition pp(position);
			FORMATTER_OBJECT(nfo)->parse(ustr, result, pp);

			if (pp.getErrorIndex() >= 0) {
				INTL_DATA_ERROR_CODE(nfo) = U_PARSE_ERROR;
			} else {
				position = pp.getIndex();
				switch(type) {
					case FORMAT_TYPE_INT32:
						RETVAL_LONG(result.getLong(INTL_DATA_ERROR_CODE(nfo)));
						break;
					case FORMAT_TYPE_INT64:
					{
						int64_t val64 = result.getInt64(INTL_DATA_ERROR_CODE(nfo));
						if(val64 > ZEND_LONG_MAX || val64 < ZEND_LONG_MIN) {
							RETVAL_DOUBLE(val64);
						} else {
							RETVAL_LONG((zend_long)val64);
						}
						break;
					}
					case FORMAT_TYPE_DOUBLE:
						RETVAL_DOUBLE(result.getDouble(INTL_DATA_ERROR_CODE(nfo)));
						break;
				}
			}
			break;
		}
		case FORMAT_TYPE_CURRENCY:
			if (hasThis()) {
				const char *space;
				const char *class_name = get_active_class_name(&space);
				zend_argument_value_error(2, "cannot be NumberFormatter::TYPE_CURRENCY constant, "
					"use %s%sparseCurrency() method instead", class_name, space);
			} else {
				zend_argument_value_error(3, "cannot be NumberFormatter::TYPE_CURRENCY constant, use numfmt_parse_currency() function instead");
			}
			goto cleanup;
		default:
			zend_argument_value_error(hasThis() ? 2 : 3, "must be a NumberFormatter::TYPE_* constant");
			goto cleanup;
	}

	if (zposition) {
		position = numfmt_utf16_offset_to_utf8(ustr, position);
		ZEND_TRY_ASSIGN_REF_LONG(zposition, position);
	}

cleanup:

#if ICU_LOCALE_BUG && defined(LC_NUMERIC)
	setlocale(LC_NUMERIC, oldlocale);
	efree(oldlocale);
#endif

	INTL_METHOD_CHECK_STATUS( nfo, "Number parsing failed" );
}
/* }}} */

/* {{{ Parse a number as currency. */
U_CFUNC PHP_FUNCTION( numfmt_parse_currency )
{
	char *str;
	size_t str_len;
	int32_t position = 0;
	zval *zcurrency, *zposition = NULL;
	FORMATTER_METHOD_INIT_VARS;

	/* Parse parameters. */
	if( zend_parse_method_parameters( ZEND_NUM_ARGS(), getThis(), "Osz|z!",
		&object, NumberFormatter_ce_ptr,  &str, &str_len, &zcurrency, &zposition ) == FAILURE )
	{
		RETURN_THROWS();
	}

	/* Fetch the object. */
	FORMATTER_METHOD_FETCH_OBJECT;

	/* Convert given string to UTF-16. */
	icu::UnicodeString ustr;
	intl_stringFromChar(ustr, str, str_len, &INTL_DATA_ERROR_CODE(nfo));
	INTL_METHOD_CHECK_STATUS( nfo, "String conversion to UTF-16 failed" );

	if (zposition) {
		zend_long long_position = zval_get_long(zposition);
		if (UNEXPECTED(long_position < INT32_MIN || long_position > INT32_MAX)) {
			zend_argument_value_error(hasThis() ? 3 : 4, "must be between %d and %d", INT32_MIN, INT32_MAX);
			RETURN_THROWS();
		}
		position = (int32_t) long_position;
		if (!numfmt_utf8_offset_to_utf16(str, str_len, &position, &INTL_DATA_ERROR_CODE(nfo))) {
			INTL_METHOD_CHECK_STATUS(nfo, "Invalid UTF-8 offset");
		}
	}

	icu::ParsePosition pp(position);
	std::unique_ptr<icu::CurrencyAmount> currAmt(FORMATTER_OBJECT(nfo)->parseCurrency(ustr, pp));

	if (currAmt == nullptr || pp.getErrorIndex() >= 0) {
		INTL_DATA_ERROR_CODE(nfo) = U_PARSE_ERROR;
		INTL_METHOD_CHECK_STATUS( nfo, "Number parsing failed" );
	}

	if(zposition) {
		position = numfmt_utf16_offset_to_utf8(ustr, pp.getIndex());
		ZEND_TRY_ASSIGN_REF_LONG(zposition, position);
	}

	const double number = currAmt->getNumber().getDouble(INTL_DATA_ERROR_CODE(nfo));

	/* Convert parsed currency to UTF-8 and pass it back to caller. */
	icu::UnicodeString ucurrency(currAmt->getISOCurrency());

	zend_string *u8str = intl_charFromString(ucurrency, &INTL_DATA_ERROR_CODE(nfo));
	INTL_METHOD_CHECK_STATUS( nfo, "Currency conversion to UTF-8 failed" );
	ZEND_TRY_ASSIGN_REF_STR(zcurrency, u8str);

	RETVAL_DOUBLE( number );
}
/* }}} */
