using Php;

namespace PhpNative {
    public string number_format_static (double value, int decimals, string dec_point, string thousands_sep, string php_file, int php_line) throws Error {
        string formatted = ("%.*f").printf (decimals, value);
        if (dec_point != ".") {
            formatted = formatted.replace (".", dec_point);
        }

        if (thousands_sep != "") {
            int dot_index = formatted.index_of (dec_point);
            string integer_part = dot_index >= 0 ? formatted.substring (0, dot_index) : formatted;
            string fraction_part = dot_index >= 0 ? formatted.substring (dot_index) : "";
            bool negative = integer_part.has_prefix ("-");
            if (negative) {
                integer_part = integer_part.substring (1);
            }

            var grouped = new StringBuilder ();
            int digits = 0;
            for (int i = integer_part.length - 1; i >= 0; i--) {
                if (digits > 0 && digits % 3 == 0) {
                    grouped.prepend (thousands_sep);
                }
                grouped.prepend_c (integer_part[i]);
                digits++;
            }

            formatted = (negative ? "-" : "") + grouped.str + fraction_part;
        }

        return formatted;
    }

    public zval number_format_zval (zval value, zval decimals, zval dec_point, zval thousands_sep, string php_file, int php_line) throws Error {
        return zval.string_value (number_format_static (zval_to_double (value), zval_to_int (decimals), zval_to_string (dec_point), zval_to_string (thousands_sep), php_file, php_line));
    }
}
