<?php

namespace Velis\Notification;

use Velis\App;
use Velis\Arrays;
use Velis\Exception;
use Velis\Notification\Mobile\FcmClientFactory;
use Velis\Queue\AbstractJob;
use Velis\Queue\QueueInterface;

/**
 * Mobile notification queue model
 * @author Damian Kurek <damian.kurek@velis.pl>
 */
class MobileQueue extends AbstractJob
{
    /**
     * Message to send
     * @var array
     */
    private array $message;

    /**
     * {@inheritDoc}
     * @throws Exception
     */
    public function perform(): void
    {
        $this->setMessage($this->args['message']);
        $this->performRequest();
    }

    /**
     * Sets message to send
     * @param array $message
     */
    private function setMessage(array $message): void
    {
        $this->message = $message;
    }

    /**
     * {@inheritDoc}
     */
    protected function getQueueName(): string
    {
        return 'mobile';
    }

    /**
     * Send push notification
     * @param array $message
     * @throws Exception
     */
    public static function send(array $message): void
    {
        $instance = new self();
        $instance->setMessage($message);
        $instance->exec();
    }

    /**
     * @return void
     * @throws Exception
     */
    private function exec(): void
    {
        if (App::$config->resque->enabled && in_array('mobile', Arrays::toArray(App::$config->resque->workers))) {
            $this->scheduleNotification();
        } else {
            $this->performRequest();
        }
    }

    /**
     * Sends request to google API
     * @throws Exception
     */
    private function performRequest(): void
    {
        $clientFactory = new FcmClientFactory(App::$config->fcm->authConfigPath);
        $client = $clientFactory->create();

        $client->post(App::$config->fcm->url, [
            'json' => [
                'message' => $this->message,
            ],
        ]);

        MobileLog::log($this->message);
    }

    /**
     * Adds message to queue
     * @return void
     */
    private function scheduleNotification(): void
    {
        /** @var QueueInterface $queue */
        $queue = App::getService('queue');

        $this->setParams([
            'message' => $this->message,
        ]);

        $this->addToQueue($queue);
    }
}
