<?php

namespace App\Http\Services\V1;

use App\Generated\V1\DTOs\TimMessageDTO;
use App\Generated\V1\Messages\Im\MarkUserMessagesReadMessage;
use App\Generated\V1\Messages\Im\DeleteMessage;
use App\Generated\V1\Messages\Im\RevokeMessage;
use App\Generated\V1\Messages\Im\SendMessage;
use App\Generated\V1\Messages\Im\GetUsersLatestsMessage;
use App\Http\Controllers\Miniprogram\Auth;
use App\Managers\IMManager;
use App\Utils\ImUtil;

class ImService
{
    protected $imUtil;
    protected $imManager;

    public function __construct(ImUtil $imUtil, IMManager $imManager)
    {
        $this->imUtil = $imUtil;
        $this->imManager = $imManager;
    }

    public function markUserMessagesRead(MarkUserMessagesReadMessage $message)
    {
        $timMessage = $message->getMessage();


        $msgRandom = $timMessage->getMsgRandom();
        $msgTimeStamp = $timMessage->getMsgTimeStamp();
        $msgSeq = $timMessage->getMsgSeq();

        $uid = Auth::auth();

        $map = $this->imManager->mapAccountToUserId([
            $fromAccount = $timMessage->getFromAccount(),
            $toAccount = $timMessage->getToAccount(),
        ]);

        $this->imManager->markMessageAsRead($uid, $map[$fromAccount] ?? 0, $map[$toAccount] ?? 0, $msgTimeStamp, $msgRandom, $msgSeq);
    }

    public function delete(DeleteMessage $message)
    {
        $timMessage = $message->getMessage();


        $msgRandom = $timMessage->getMsgRandom();
        $msgTimeStamp = $timMessage->getMsgTimeStamp();
        $msgSeq = $timMessage->getMsgSeq();

        $uid = Auth::auth();

        $map = $this->imManager->mapAccountToUserId([
            $fromAccount = $timMessage->getFromAccount(),
            $toAccount = $timMessage->getToAccount(),
        ]);

        $this->imManager->deleteMessage($uid, $map[$fromAccount] ?? 0, $map[$toAccount] ?? 0, $msgTimeStamp, $msgRandom, $msgSeq);
    }

    public function revoke(RevokeMessage $message)
    {
        $timMessage = $message->getMessage();


        $msgRandom = $timMessage->getMsgRandom();
        $msgTimeStamp = $timMessage->getMsgTimeStamp();
        $msgSeq = $timMessage->getMsgSeq();

        $uid = Auth::auth();

        $map = $this->imManager->mapAccountToUserId([
            $fromAccount = $timMessage->getFromAccount(),
            $toAccount = $timMessage->getToAccount(),
        ]);

        $this->imManager->revokeMessage($uid, $map[$toAccount] ?? 0, $msgTimeStamp, $msgRandom, $msgSeq);
    }

    public function send(SendMessage $message)
    {
        $message->getMessage();
    }

    public function getUsersLatests(GetUsersLatestsMessage $message)
    {
        $uids = $message->getUids();

        $uid = Auth::auth();

        $timMessages = $this->imManager->getUserLatestMessages($uid, $uids);

        $message->setResponse(TimMessageDTO::initFromEloquents($timMessages));
    }
}
