<?php

namespace Velis\Notification;

use Velis\App;

/**
 * Redis message model
 * @author Damian Kurek <damian.kurek@velis.pl>
 */
class RedisMessage
{
    /**
     * Message to send
     * @var array
     */
    protected array $message;

    /**
     * Message users
     * @var array
     */
    protected array $users;


    /**
     * Creates new message instance
     * @param array $message
     * @param array $users
     */
    public function __construct(array $message, array $users)
    {
        $this->message = $message;
        $this->users = $users;
    }


    /**
     * Publishes message to redis server
     * @return int|bool
     */
    public function publish()
    {
        if (App::$config->node->pushNotification && class_exists('Redis')) {
            $redis = new \Redis();

            $this->message['users'] = $this->users;
            $this->message['instance'] = self::getPrefix();

            if ($redis->connect(App::$config->node->redisAddress)) {
                return $redis->publish(self::getStore(), json_encode($this->message));
            }
        }

        return false;
    }


    public static function getPrefix(): string
    {
        return App::$config->session->prefix ?: md5(App::$config->db->database);
    }

    public static function getStore(): string
    {
        if (App::$config->node->redis->channel) {
            return App::$config->node->redis->channel;
        }
        return 'nodeStore-' . App::$config->db->database;
    }
}
