<?php


namespace Ezypay\Result;


use Ezypay\Object\ObjectFactory;

/**
 * Class ResultFactory
 *
 * @package Ezypay\Result
 */
class ResultFactory extends ResultAbstractFactory
{


    /**
     * Execute call and create resut
     * 
     * @return \result
     */
    public function run()
    {
        $res = $this->res;
        $err = $this->err;

        if (!empty($err)) {

            return ResultFactory::createInstance('ResultError', array(
                'data' => $err
            ));
        }

        if (array_key_exists('data', $res)) {
            $objectArray = array_map(array($this, "makeObject"), $res['data']);
            $properties = array(
                'totalReturned' => $res['totalReturned'],
                'totalRecord' => $res['totalRecord'],
                'data' => $objectArray
            );

            return $this->createInstance('ResultList', $properties);

        } elseif (array_key_exists('paymentMethod', $res)) // Subsrciption update has different structure of  result
        {
            $properties = array(
                'data' => $this->makeObject($res['paymentMethod'])
            );
            return $this->createInstance('ResultSingle', $properties);
        } else { // result single object
            $properties = array(
                'data' => $this->makeObject($res)
            );
            return $this->createInstance('ResultSingle', $properties);
        }
    }

    /**
     * Object Factory
     *
     * Create object from provided data
     *
     * @param $name string Class name
     * @param $data array array of the property values
     * @return mixed
     */
    private function createInstance($name, $data)
    {
        if (class_exists('Ezypay\\Result\\' . $name)) {
            $class = 'Ezypay\\Result\\' . $name;
            return new $class($data);
        }
    }

    /**
     * makeObject
     *
     * @param $data array response array data
     * @return \Ezypay\Object[]
     */
    private function makeObject($data)
    {
        if (!$data) {
            return false;
        }

        return ObjectFactory::createObject($this->resourceType, $data);
    }

}
