using Php;

namespace PhpNative {
    public string pack_string_static (string format, string value, string php_file, int php_line) throws Error {
        if (format != "H*") {
            return value;
        }

        string hex = value.replace (" ", "").replace ("\t", "").replace ("\n", "").replace ("\r", "");
        var builder = new StringBuilder ();
        for (int i = 0; i + 1 < hex.length; i += 2) {
            int high = hex_nibble (hex[i]);
            int low = hex_nibble (hex[i + 1]);
            if (high < 0 || low < 0) {
                continue;
            }
            builder.append_c ((char) ((high << 4) | low));
        }
        return builder.str;
    }

    private int hex_nibble (char ch) {
        if (ch >= '0' && ch <= '9') {
            return ch - '0';
        }
        if (ch >= 'a' && ch <= 'f') {
            return ch - 'a' + 10;
        }
        if (ch >= 'A' && ch <= 'F') {
            return ch - 'A' + 10;
        }
        return -1;
    }

    public zval pack_zval (zval format, zval value, string php_file, int php_line) throws Error {
        return zval.string_value (pack_string_static (zval_to_string (format), zval_to_string (value), php_file, php_line));
    }
}
