import {CommandHandler, ICommandHandler} from "@nestjs/cqrs";
import {PostCardsToUserCommand} from "../../game/commands/post-cards-to-user.command";
import {Inject, Logger} from "@nestjs/common";
import {ClientProxy} from "@nestjs/microservices";
import {SharedService} from "../../shared/shared.service";
import { Messages} from "../../messaging/tg.text";
import {CommandsConsts} from "../../Consts/commands.consts";

@CommandHandler(PostCardsToUserCommand)
export class TgPostCardsToUserCommandHandler implements ICommandHandler<PostCardsToUserCommand> {
  private readonly logger = new Logger(TgPostCardsToUserCommandHandler.name);
  constructor(
    @Inject('Telegram') private telegramService: ClientProxy,
    private sharedService: SharedService,
  ) {
  }


  async execute(command: PostCardsToUserCommand): Promise<any> {
    const extra = {
      reply_markup: {
        keyboard: [],
      },
    };
    const extra_Inline = {
      reply_markup: {
        inline_keyboard: [],
      },
    }
    if (command.cards.length === 0) {
      this.telegramService.emit({ cmd: CommandsConsts.SendMessage }, { chatId: command.chatId, message: "У вас нет карт которые можно сейчас использовать"});
      return;
    }


    command.cards.forEach((card) => {
      extra.reply_markup.keyboard.push([
        {text: Messages.EMOJI_CARD + ' ' + card},
      ]);
      extra_Inline.reply_markup.inline_keyboard.push([{ text: Messages.EMOJI_CARD + ' ' + card, callback_data: `card/${card}`}])
    });
    await this.sharedService.setConfig(`buttons_${command.chatId}`,
      JSON.stringify(extra),
    );
    this.logger.verbose(`send buttons, inline: ${command.inline}`);
    this.telegramService.emit({cmd: CommandsConsts.SendMessage}, {
      chatId: command.chatId,
      message: Messages.SELECT_CARD,
      extra: command.inline ? extra_Inline : extra
    });
  }
}