<?php

class Remote_hub_model extends Cf_Model
{
    public const SUPERHUB_ROLE = 'superhub';
    public const DEFAULT_MODE = 'pull_over_rsync';
    public const DEFAULT_SSH_USER = 'cftransport';

    /**
     * @param $data
     */
    public function addRemoteHub($data)
    {
        $this->getRestClient()->post('/fr/remote-hub', $this->prepareRemoteHubData($data));
        $this->generateConfigFile();
    }

    /**
     * @param $id
     * @param $data
     */
    public function updateRemoteHub($id, $data)
    {
        $this->getRestClient()->put('/fr/remote-hub/' . $id, $data);
        $this->generateConfigFile();
    }

    /**
     * @param $id
     * @param $state
     */
    public function updateTargetState($state)
    {
        $this->getRestClient()->put('/fr/hub-state', ['target_state' => $state]);
        $this->generateConfigFile();
    }

    /**
     * @param array $data
     *
     * @return array
     */
    private function prepareRemoteHubData(array $data): array
    {
        return [
            'ui_name' => $data['hostname'],
            'hostkey' => $data['hostkey'],
            'api_url' => $data['server'],
            'target_state' => $data['target_state'],
            'role' => $data['role'],
            'transport' => [
                'mode' => isset($data['transportMethod']) ? $data['transportMethod'] : self::DEFAULT_MODE,
                'ssh_user' => self::DEFAULT_SSH_USER,
                'ssh_host' => parse_url($data['server'])['host'],
                'ssh_pubkey' => isset($data['sshKey']) ? $data['sshKey'] : '',
                'ssh_fingerprint' => isset($data['sshFingerprint']) ? $data['sshFingerprint'] : '',
            ],
        ];
    }

    /**
     * @return mixed
     */
    public function getSuperHub()
    {
        $remoteHubs = $this->getRemoteHubs();
        foreach ($remoteHubs as $remoteHub) {
            if ($remoteHub['role'] == self::SUPERHUB_ROLE) {
                return $remoteHub;
            }
        }

        return null;
    }

    /**
     * @return mixed
     */
    public function getRemoteHubs()
    {
        return json_decode($this->getRestClient()->get('/fr/remote-hub?expand=statistics'), JSON_OBJECT_AS_ARRAY);
    }

    /**
     * @param $id
     *
     * @return mixed
     */
    public function getRemoteHub($id)
    {
        return json_decode($this->getRestClient()->get('/fr/remote-hub/' . $id), JSON_OBJECT_AS_ARRAY);
    }

    /**
     * @return void
     */
    public function generateConfigFile()
    {
        $this->getRestClient()->post('/fr/federation-config', []);
    }
}
