<?php

namespace FR\V1_0\Controllers;

use FR\V1_0\ConfigFile\ConfigFile;
use FR\V1_0\Entities\RemoteHub\RemoteHub;
use FR\V1_0\Entities\RemoteHub\RemoteHubsCollection;
use FR\V1_0\Models\ConfigFileModel;
use FR\V1_0\Models\SetupHubModel;

/**
 * @uri /fr/v1.0/setup-hub/:role
 * @uri /fr/setup-hub/:role
 */
class SetupHub extends \CfProtectedResource
{
    /**
     * @param $request
     * @param $role
     *
     * @rbacName Enable hub
     * @rbacGroup Federation report API
     * @rbacAlias setupHub.enable
     *
     * @return \Response
     * @throws \Exception
     */
    public function post($request, $role)
    {
        $setupHubModel = new SetupHubModel(\CfSettings::getInstance()->getConnection(), $this->username, $role);
        $response = new \Response($request);

        if ($setupHubModel->getHubRole()) {
            $response->code = \Response::UNPROCESSABLE_ENTITY;
            $response->body = sprintf(
                'Hub has already received request to be enabled as `%s`',
                $setupHubModel->getHubRole()
            );
            $response->code = \Response::BADREQUEST;
            return $response;
        }

        $configEntity = new ConfigFile();
        $configEntity->setRemoteHubs(new RemoteHubsCollection());
        $configEntity->setRole($role);
        $configEntity->setTargetState(RemoteHub::TARGET_STATE_ON);

        // write the config file which is needed for the policy to prepare hub
        $configFileModel = new ConfigFileModel();
        $configFileModel->save(json_encode($configEntity, JSON_PRETTY_PRINT));

        $setupHubModel->enable();
        $response->code = \Response::ACCEPTED;
        return $response;
    }

}

/**
 * @uri /fr/v1.0/hub-status
 * @uri /fr/hub-status
 */
class HubStatus extends \CfProtectedResource
{
    /**
     * @param $request
     *
     * @rbacName Get hub status
     * @rbacGroup Federation report API
     * @rbacAlias hubStatus.get
     * @rbacAllowedByDefault
     *
     * @return \Response
     */
    public function get($request)
    {
        $setupHubModel = new SetupHubModel(\CfSettings::getInstance()->getConnection(), $this->username);
        $response = new \Response($request);
        $response->body = json_encode([
            'configured' => $setupHubModel->isConfigured(),
            'role' => $setupHubModel->getRole(),
            'enable_request_sent' => (bool) $setupHubModel->getValueByKey(SetupHubModel::ENABLE_REQUEST_SENT),
            'transport_ssh_public_key' => $setupHubModel->getPublicKey(),
            'ssh_fingerprint' => $setupHubModel->getSshFingerPrint(),
            'target_state' => $setupHubModel->getTargetState()
        ]);
        $response->code = \Response::OK;
        return $response;
    }
}
