<?php
namespace Shared;

abstract class AbstractREST
{
    protected $path;
    protected $class;
    protected $id;
    protected $subclass;
    protected $subID;
    protected $method;

    public function __construct()
    {

        $this->path=$_REQUEST["path"];
        $arr =explode("/",$this->path);
        if(count($arr)==1)
            $this->class=@$arr[0];
        else
        {
            $this->class=@$arr[0];
            $this->id=intval(@$arr[1]);
            $this->subclass=@$arr[2];
            $this->subID=@$arr[3];
        }//var_dump($this);
        $this->method= $_SERVER['REQUEST_METHOD'];//var_dump($this);
    }
    
    public function Respond()
    {
       try{
            $result=false;
            //$_SERVER['REQUEST_METHOD']
            switch($this->method) 
            {
                case "GET":  
                    $result=$this->getRespond($_GET);break;
                case "POST": 
                    $result=$this->postRespond($_POST);break;
                case "PUT":  
                        $data=json_decode(file_get_contents("php://input"),true);
                        $result=$this->putRespond($data);break;
                case "DELETE": 
                    $data=null;
                    $result=$this->deleteRespond($data);break;
            }
        }
        catch(\Exception $e)
        {
            \Shared\Messages::Error($e->getMessage());
        }
        return $this->wrapEncode($result);
        
    }
    
    protected function wrapEncode($r)
    {
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");
        //\Shared\Debug::Instance()->Activate()->Display("test",true)->Deactivate();
        echo json_encode(array(
                    "status"=>"ok",
                    "data"=>$r,
                    "messages"=>(\Shared\Messages::GetAll()))
        );
    }

    protected function getRespond($data)
    {
        http_response_code(403);
        die();
    }

    protected function postRespond($data)
    {
        http_response_code(403);
        die();
    }
    protected function putRespond($data)
    {
        http_response_code(403);
        die();
    }
    protected function deleteRespond($data)
    {
        http_response_code(403);
        die();
    }

}