<?php

namespace events\listeners;

use events\BaseEvents;
use events\EventService;

class FederatedReportingEvents extends BaseEvents
{
    public static function registerEvents()
    {
        self::stateChanged();
    }

    private static function stateChanged()
    {
        EventService::addEventListener(BaseEvents::CHANGED_HUB_STATE, function ($data) {
            $userRoles = (new \CfUsers($data['user']))->getUserRoles();
            // proceed if user can trigger an agent run
            if (\RbacAccessService::isActionAllowed('actions.agent_run', (new \CfRBAC())->getPermissionsByRoles($userRoles))) {
                $hubInfo = (new \CfHub(\CfdbPdo::getInstance()->getConnection()))->getHubInfo();
                if (!isset($hubInfo['hostkey']) || empty($hubInfo['hostkey'])) {
                    syslog(LOG_DEBUG, 'Cannot retrieve hostkey while triggering an agent run on hub state change');
                }
                $cfActions = new \CfActions(\CfdbPdo::getInstance()->getConnection(), $data['user']);
                $cfActions->agent_run((object) ['hostkey' => $hubInfo['hostkey']]);
            }
        });
    }
}
