<?php

class Core_Detector_Response
{
    /**
     * @var array
     */
    protected $_data = array();

    public function __construct($jsonResponse = null) {
        if ($this->_isValidJson($jsonResponse)) {
            $this->_data = json_decode($jsonResponse);
        }
    }

    /**
     * @param array $data
     *
     * @return \Core_Detector_Response
     */
    public function setData($data)
    {
        $this->_data = (array) $data;
        return $this;
    }

    /**
     * @return array
     */
    public function getData()
    {
        return $this->_data;
    }

    /**
     * Set detection ID
     * @param  int     $id
     * @return \Core_Detector_Response
     */
    public function setDetectionId($id)
    {
        $this->_responseData['detection_id']    = $id;
        return $this;
    }

    /**
     * Get detection ID
     * @return  string
     */
    public function getDetectionId()
    {
        return $this->_responseData['detection_id'];
    }


    public function __toString()
    {
        return json_encode($this->_responseData);
    }

    /**
     * Reduces response to set of required fields specified
     * @param  array   $properties
     * @return type
     */
    public function reduceTo(array $properties)
    {
        $data    = $this->getData();
        $newData = array();
        foreach ($properties as $property) {
            $names = explode('.', $property);

            // get value to insert and reference to location where to insert
            $value =  $this->_findLocation($names, $data);
            $place = &$this->_findLocation($names, $newData);

            $place = $value;

        }
        $this->setData($newData);
        return $this;
    }

    private function &_findLocation($names, &$data)
    {
        $pointer    = &$data;
        foreach($names as $name) {
            if (!isset($pointer[$name])) {
                $pointer[$name] = array();
            }
            $pointer = &$pointer[$name];
        }
        return $pointer;
    }



    /**
     * Check if received string is a valid JSON response
     * @param   string  $string
     * @return  boolean
     */
    protected function _isValidJson($string)
    {
        $json = json_decode($string);
        return ($json !== false);
    }
}