<?php

namespace Shm\ShmChat\SchemaChat;

use Shm\Collection\Collection;
use Shm\Shm;
use Shm\ShmChat\ShmChat;
use Shm\ShmDB\mDB;
use Shm\ShmTypes\StructureType;

class ShmChannels extends Collection
{


    private static $joinablePipelineHandler;

    public static function setJoinablePipelineHandler(callable $pipelineHandler)
    {
        self::$joinablePipelineHandler = $pipelineHandler;
    }

    public static function hasJoinablePipelineHandler(): bool
    {
        return self::$joinablePipelineHandler !== null;
    }

    public static function getJoinablePipelineHandler(): array
    {

        if (self::$joinablePipelineHandler) {
            return (self::$joinablePipelineHandler)();
        }

        return [];
    }


    public function schema(): ?StructureType
    {
        $schema = Shm::structure([
            "name" => Shm::string(),
            'lastMessage' => ShmChannelMessages::ID(),
            "payload" =>  Shm::structure([
                "*" => Shm::mixed()
            ]),

            'unreadCounts' => Shm::structure([
                '*' => Shm::int()
            ]),

            'type' => Shm::enum([
                'default' => 'Обычный чат',
                'support' => 'Поддержка',
                'supportSystem' => 'Поддержка системы',
            ])->default('default'),
        ]);



        return $schema;
    }

    public static function zeroUnreadCounts($channelId, $memberId)
    {
        $channel = ShmChannels::structure()->findOne(['_id' =>  mDB::id($channelId)]);
        if (!$channel) return;

        $unreadCounts =  $channel->unreadCounts ?? [];


        $unreadCounts = (array) $unreadCounts;

        $unreadCounts[(string) $memberId] = 0;

        ShmChannels::structure()->_updateOne(['_id' => mDB::id($channelId)], ['$set' => ['unreadCounts' => $unreadCounts]]);
    }

    public static function updateUnreadCounts($channelId)
    {


        $members = ShmChannelMembers::structure()->find(['channel' => mDB::id($channelId), 'removed' => false, 'banned' => false, 'muted' => false]);


        $channel = ShmChannels::structure()->findOne(['_id' => mDB::id($channelId)]);

        $beforeUnreadCounts = $channel->unreadCounts ?? [];

        $unreadCounts = [];

        foreach ($members as $member) {

            $memberId = (string) $member->_id;
            $currentUnreadCount = $beforeUnreadCounts[$memberId] ?? 0;
            $newUnreadCount = $currentUnreadCount + 1;
            $unreadCounts[$memberId] = $newUnreadCount;
        }

        ShmChannels::structure()->_updateOne(['_id' => $channel->_id], ['$set' => ['unreadCounts' => $unreadCounts]]);
    }
}