import {Controller, Logger} from "@nestjs/common";
import {MessagePattern, Payload} from "@nestjs/microservices";
import {CommandsConsts} from "../Consts/commands.consts";
import {ValidateAnswerInline, ValidateAnswerModel} from "./models/validate-answer.model";
import {QuizAnsweredEvent} from "../game/events/quiz.answered";
import {QuizService} from "../quiz/quiz.service";
import {CommandBus, EventBus} from "@nestjs/cqrs";
import {SendBetweenRoundsActionsCommand} from "../guests/command/send-between-rounds-actions.command";
import {DebuffCardPlayedEvent} from "../game/events/debuff-card-played.event";
import {GameService} from "../game/game.service";

@Controller()
export class QuizMessagingController {
  private readonly logger = new Logger(QuizMessagingController.name);
  constructor(private quizService: QuizService, private eventBus: EventBus, private cmdBus: CommandBus, private gameService: GameService) {
  }


  @MessagePattern({ cmd: CommandsConsts.QuestionAnswer})
  async getQuestionAnswer(@Payload() data: ValidateAnswerInline) {
    this.logger.verbose(`Validate answer ${data}`);
    this.eventBus.publish(new QuizAnsweredEvent(data.name));
    const result = await this.quizService.validateAnswerInline(
      data.answer,
      data.user,
    );
    return { valid: result }
  }

  @MessagePattern({ cmd: CommandsConsts.CompleteQueue})
  async completeQueueItem(@Payload() data: any) {
    this.logger.verbose(`complete item`)
    await this.gameService.markQueueAsCompleted(null);
    //await this.quizService.proceedWithGame();
  }

  @MessagePattern({ cmd: CommandsConsts.GetCards})
  async getCardsForUser(@Payload() data: { user: number, inline: boolean}) {
    this.logger.verbose(`getCardsForUser ${data}`);
    await this.cmdBus.execute(new SendBetweenRoundsActionsCommand(data.user, true))
  }

  @MessagePattern({ cmd: CommandsConsts.ApplyDebuff})
  async applyDebuf(@Payload() data: any) {
    const actionData = JSON.parse(data.data);
    this.eventBus.publish(new DebuffCardPlayedEvent(actionData.card, actionData.value, +data.from, +actionData.user))
  }

}