<?php

/**
 * @uri /ssh-key
 */
class SshKey extends CfProtectedResource
{
    private $cfSshKey;

    public function __construct($parameters)
    {
        parent::__construct($parameters);
        $this->cfSshKey = new CfSshKeys();
    }

    /**
     * @rbacName Generate SSH key
     * @rbacGroup Generate SSH API
     * @rbacAlias ssh.post
     */
    public function post($request): Response
    {
        $response = new Response($request);
        $sshKeyEntity = $this->cfSshKey->generate();
        $sshKeyEntity->setGeneratedBy($this->username);
        $id = $this->cfSshKey->save($sshKeyEntity);
        $response->body = json_encode(['id' => $id, 'public_key' => $sshKeyEntity->getPublicKey()]);
        return $response;
    }

    /**
     * @rbacName SSH keys list
     * @rbacGroup Generate SSH API
     * @rbacAlias ssh.get
     */
    public function get($request): Response
    {
        $response = new Response($request);
        $response->code = Response::OK;
        $response->body = json_encode($this->cfSshKey->list());
        return $response;
    }
}

/**
 * @uri /ssh-key/:id
 */
class SshKeyItem extends CfProtectedResource
{
    private $cfSshKey;

    public function __construct($parameters)
    {
        parent::__construct($parameters);
        $this->cfSshKey = new CfSshKeys();
    }

    /**
     * @rbacAlias ssh.get
     */
    public function get($request, $id): Response
    {
        $response = new Response($request);
        $response->code = Response::OK;
        if ($key = $this->cfSshKey->get(intval($id))) {
            $response->body = json_encode($key);
        } else {
            $response->code = Response::NOTFOUND;
        }

        return $response;
    }

    /**
     * @rbacName Remove SSH key
     * @rbacGroup Generate SSH API
     * @rbacAlias ssh.delete
     */
    public function delete($request, $id): Response
    {
        $response = new Response($request);
        $response->code = Response::NOCONTENT;
        $response->body = json_encode($this->cfSshKey->delete(intval($id)));
        return $response;
    }
}
