<?php

/**
 * @uri /actions/:action_id
 */
class Actions extends CfProtectedResource
{
    private $cfActionsModel;
    public function __construct($parameters)
    {
        parent::__construct($parameters);
        $this->cfActionsModel = new CfActions(CfdbPdo::getInstance()->getConnection(), $this->username);
    }

    public function post($request, $action_id)
    {
        try {
            $response = new Response($request);
            $data = Utils::getValidJsonData($request->data);
            // check if requested action exists and throw exception if not
            if (!method_exists($this->cfActionsModel, $action_id)) {
                throw new Exception("Action `$action_id` does not exist");
            }
            // call action from cfActionsModel
            $actionResponse = $this->cfActionsModel->{$action_id}($data);
            $response->body = (is_string($actionResponse) ? $actionResponse : json_encode($actionResponse));
            $response->code = \Response::ACCEPTED;
            return $response;
        } catch (Exception $exception) {
            $response->code = Response::BADREQUEST;
            $response->body = $exception->getMessage();
            return $response;
        }
    }
}
