<?PHP

class JsonHelper
{

    private $Data;
    private $Warnings;

    public function __construct()
    {
        $this->Data = array();
        $this->Warnings = array();
    }

    public function AddDatum($Key, $Value)
    {
        $this->Data[$Key] = $Value;
    }

    public function AddWarning($Message)
    {
        $this->Warnings[] = strval($Message);
    }

    public function Error($Message)
    {
        $this->SendResult($this->GenerateResult("ERROR", $Message));
    }

    public function Success($Message="")
    {
        $this->SendResult($this->GenerateResult("OK", $Message));
    }

    private function SendResult(array $Result)
    {
        global $SysConfig;
        header("Content-Type: application/json; charset="
            .$SysConfig->DefaultCharacterSet(), TRUE);
        print $this->ArrayToJson($Result);
    }

    private function GenerateResult($State, $Message)
    {
        return array(
            "data" => $this->Data,
            "status" => array(
                "state" => strval($State),
                "message" => strval($Message),
                "numWarnings" => count($this->Warnings),
                "warnings" => $this->Warnings));
    }

    private function ArrayToJson(array $Array)
    {
        global $SysConfig;

        # initialize
        $JSON = "";
        $counter = 0;

        foreach ($Array as $key => $value)
        {
            # add key
            $JSON .= "'".$key."':";

            # recur if the value is an array
            if (is_array($value))
            {
                $JSON .= $this->ArrayToJson($value);
            }

            # add the value
            else
            {
                # escape
                $value = str_replace("\r", "", $value);
                $value = htmlentities($value, ENT_QUOTES, $SysConfig->DefaultCharacterSet());

                # if the value is a number, parse it and don't put in quotes
                if (is_numeric($value))
                {
                    $JSON .= intval($value);
                }

                # for everything else, get the string value and put in quotes
                else
                {
                    $JSON .= "'".strval($value)."'";
                }
            }

            # add comma if necessary
            $counter++;
            $JSON .= ($counter < count($Array)) ? "," : "" ;
        }

        # return JSON-ified array
        return "{".$JSON."}";
    }

}

?>
