<?php

namespace FR\V1_0\Models;

class RemoteHubStatisticsModel
{
    /**
     * @var \PDO
     */
    private $cfPdo;
    private $userName;

    public function __construct(\PDO $cfPdo, $userName)
    {
        $this->cfPdo = $cfPdo;
        $this->userName = $userName;
    }

    /**
     * @param $hostkey
     *
     * @return array
     */
    public function getStatistics($hostkey)
    {
        $hubId = $this->getHubIdByHostkey($hostkey);
        return [
            'bootstrappedHostsCount' => $hubId > 0 ? $this->getBootstrappedHostsCount($hubId) : 0,
            'timeOfLastImport' => $hostkey ? $this->getLastImportTimestamp($hostkey) : 0
        ];
    }

    /**
     * @param $hostkey
     *
     * @return integer|null
     */
    private function getHubIdByHostkey($hostkey)
    {
        $statement = $this->cfPdo->prepare('SELECT hub_id FROM __hubs WHERE hostkey = :hostkey');
        $statement->execute(['hostkey' => $hostkey]);
        $result = $statement->fetch(\PDO::FETCH_ASSOC);
        return isset($result['hub_id']) ? $result['hub_id'] : null;
    }

    /**
     * @param $hubId
     *
     * @return int
     */
    private function getBootstrappedHostsCount(string $hubId)
    {
        $quotedHubId = \DatabaseHelper::quote($hubId);
        $result =  json_decode(cfapi_query_post($this->userName, "SELECT COUNT(*) FROM hosts WHERE hub_id = $quotedHubId", "", false, -1, -1, [], []), JSON_OBJECT_AS_ARRAY);
        return isset($result['data'][0]['rows'][0][0]) ? $result['data'][0]['rows'][0][0] : 0;
    }

    /**
     * @param $hubId
     *
     * @return int
     */
    private function getLastImportTimestamp($hostkey)
    {
        $statement = $this->cfPdo->prepare('SELECT last_import_ts FROM __hubs WHERE hostkey = :hostkey');
        $statement->execute(['hostkey' => $hostkey]);
        $result = $statement->fetch(\PDO::FETCH_ASSOC);
        return isset($result['last_import_ts']) ? $result['last_import_ts'] : null;
    }
}
