<?php

abstract class resource_base {

    /**  HTTP Post method */
    const HTTP_POST = 'POST';
    /**  HTTP Get method */
    const HTTP_GET = 'GET';
    /**  HTTP Put method */
    const HTTP_PUT = 'PUT';
    /**  HTTP Delete method */
    const HTTP_DELETE = 'DELETE';

    /** @var service_base Service associated with this resource. */
    private $service;
    /** @var string Type for this resource. */
    protected $type;
    /** @var string ID for this resource. */
    protected $id;
    /** @var string Template for this resource. */
    protected $template;
    /** @var array Custom parameter substitution variables associated with this resource. */
    protected $variables;
    /** @var array Media types supported by this resource. */
    protected $formats;
    /** @var array HTTP actions supported by this resource. */
    protected $methods;
    /** @var array Template variables parsed from the resource template. */
    protected $params;


    /**
     * Class constructor.
     *
     * @param service_base $service Service instance
     */
    public function __construct($service) {

        $this->service = $service;
        $this->type = 'RestService';
        $this->id = null;
        $this->template = null;
        $this->methods = array();
        $this->variables = array();
        $this->formats = array();
        $this->methods = array();
        $this->params = null;

    }

    /**
     * Get the resource ID.
     *
     * @return string
     */
    public function get_id() {

        return $this->id;

    }

    /**
     * Get the resource template.
     *
     * @return string
     */
    public function get_template() {

        return $this->template;

    }

    /**
     * Get the resource path.
     *
     * @return string
     */
    public function get_path() {

        return $this->get_template();

    }

    /**
     * Get the resource type.
     *
     * @return string
     */
    public function get_type() {

        return $this->type;

    }

    /**
     * Get the resource's service.
     *
     * @return service_base
     */
    public function get_service() {

        return $this->service;

    }

    /**
     * Get the resource methods.
     *
     * @return array
     */
    public function get_methods() {

        return $this->methods;

    }

    /**
     * Get the resource media types.
     *
     * @return array
     */
    public function get_formats() {

        return $this->formats;

    }

    /**
     * Get the resource template variables.
     *
     * @return array
     */
    public function get_variables() {

        return $this->variables;

    }

    /**
     * Execute the request for this resource.
     *
     * @param response $response  Response object for this request.
     */
    public abstract function execute($response, $date_time);

    /**
     * Parse the template for variables.
     *
     * @return array
     */
    protected function parse_template() {

        if (empty($this->params)) {
            $this->params = array();
            if (!empty($_SERVER['PATH_INFO'])) {
                $path = explode('/', $_SERVER['PATH_INFO']);
                //Check for template in lineitem, lineitems, results and scores
                $template = preg_replace('/\([0-9a-zA-Z\-,\/]+\)/', '', $this->get_template());
                $parts = explode('/', $template);
                for ($i = 0; $i < count($parts); $i++) {
                    if ((substr($parts[$i], 0, 1) == '{') && (substr($parts[$i], -1) == '}')) {
                        $value = '';
                        if ($i < count($path)) {
                            $value = $path[$i];
                        }
                        $this->params[substr($parts[$i], 1, -1)] = $value;
                    }
                }
            }
        }
        return $this->params;
    }

    /**
     * Check to make sure the request is valid.
     *
     * @param int $typeid            The typeid we want to use
     * @param string $body           Body of HTTP request message
     * @param string[] $scopes       Array of scope(s) required for incoming request
     *
     * @return boolean
     */
    public function check_tool($typeid, $body = null, $scopes = null) {

        $ok = $this->get_service()->check_tool($typeid, $body, $scopes);
        if ($ok) {
            if ($this->get_service()->get_tool_proxy()) {
                $toolproxyjson = $this->get_service()->get_tool_proxy()->toolproxy;
            }
            if (!empty($toolproxyjson)) {
                // Check tool proxy to ensure service being requested is included.
                $toolproxy = json_decode($toolproxyjson);
                if (!empty($toolproxy) && isset($toolproxy->security_contract->tool_service)) {
                    //Tip: ToolProxy check not implemented in this version, next version
                }
            } else {
                // Check that the scope required for the service request is included in those granted for the
                // access token being used.
                $permittedscopes = $this->get_service()->get_permitted_scopes();
                $ok = is_null($permittedscopes) || empty($scopes) || !empty(array_intersect($permittedscopes, $scopes));
            }
        }
        return $ok;
    }

    /**
     * Get the resource fully qualified endpoint.
     *
     * @return string
     */
    public function get_endpoint() {

        $this->parse_template();
        $template = preg_replace('/[\(\)]/', '', $this->get_template());
        $url = $this->get_service()->get_service_path() . $template;
        foreach ($this->params as $key => $value) {
            $url = str_replace('{' . $key . '}', $value, $url);
        }
        $toolproxy = $this->get_service()->get_tool_proxy();
        if (!empty($toolproxy)) {
            // $url = str_replace('{config_type}', 'toolproxy', $url);
            // $url = str_replace('{tool_proxy_id}', $toolproxy->guid, $url);
        } else {
            $url = str_replace('{config_type}', 'tool', $url);
            $url = str_replace('{tool_proxy_id}', $this->get_service()->get_type()->typeid, $url);
        }
        return $url;
    }
}