import {CommandHandler, ICommandHandler} from "@nestjs/cqrs";
import {SelectTargetPlayerCommand} from "../commands/select-target-player.command";
import {Inject, Logger} from "@nestjs/common";
import {ClientProxy} from "@nestjs/microservices";
import {MqtMessageModel} from "../../messaging/models/mqt-message.model";
import {ChatMessageRequestModel} from "../../messaging/models/chat-message-request.model";
import {CommandsConsts} from "../../Consts/commands.consts";
import {GuestsService} from "../../guests/guests.service";
import {Messages} from "../../messaging/tg.text";
//import {Promise} from "mongoose";

@CommandHandler(SelectTargetPlayerCommand)
export class SelectTargetPlayerHandler implements ICommandHandler<SelectTargetPlayerCommand> {
  private readonly logger = new Logger(SelectTargetPlayerHandler.name);
  constructor(@Inject('Telegram') private telegramService: ClientProxy,
              private guestService: GuestsService,
  ) {
  }
  async execute(command: SelectTargetPlayerCommand): Promise<any> {
    this.logger.verbose('enter');
    let allUsers = await this.guestService.findAll();
    const user = allUsers.find(x => x.telegramId === command.player);
    if(!user) {
        throw new Error(`Cant find current user ${command.player}`);
    }
    if(!command.allowSelf) {
     allUsers = allUsers.filter((x) => x.telegramId !== command.player);
    }
    const buttons = allUsers.map((x) => {
      return [{
        text: `${Messages.EMOJI_PLAYER} ${x.name}`,
        callback_data: `{ "card": "${command.debuffName}", "value": "${command.value}", "user": "${x.telegramId}" }`
      }]
    });
    console.log(buttons);

    this.telegramService.send<MqtMessageModel,ChatMessageRequestModel>(
      { cmd: CommandsConsts.SendMessage},
      {
        chatId: user.chatId,
        message: 'Выберите игрока',
        extra: {
          reply_markup: {
            inline_keyboard: [
              ...buttons
            ]
          }
        }
      }
    ).subscribe((r) => {
      this.logger.verbose(`Reply from tg service: ${r}`);
    })
  }
}