import {Controller, Logger} from "@nestjs/common";
import {Ctx, MessagePattern, Payload, RmqContext} from "@nestjs/microservices";
import {GetGuestInfoModel} from "./models/get-guest-info.model";
import {GuestsService} from "../guests/guests.service";
import {RegisterUserModel} from "./models/register-user.model";
import {SharedService} from "../shared/shared.service";
import {CommandsConsts} from "../Consts/commands.consts";
import {EventBus} from "@nestjs/cqrs";
import {PlayerCardSelectedEvent} from "../game/events/player-card-selected.event";
import {getCard} from "../helpers/card-parser";
import {QuizService} from "../quiz/quiz.service";
import {ClientNotificationType} from "../socket/socket.gateway";

@Controller()
export class GuestsMessageController {
  private readonly logger = new Logger(GuestsMessageController.name);

  constructor(private guestService: GuestsService, private sharedService: SharedService, private eventBus: EventBus, private quizService: QuizService) {
  }
  @MessagePattern({ cmd: 'GuestInfo'} )
  async getGuestInformation(@Payload() data: GetGuestInfoModel, @Ctx() context: RmqContext) {
    this.logger.log(`Message received: get user info ${JSON.stringify(data)}`);
    const user = await this.guestService.findById(data.user);
    if(!user) {
      return null;
    }
    return {
      name: user.name,
      score: user.score,
      telegramId: user.telegramId,
      chatId: user.chatId,
      prizeChance: 0,
      prizesCount: 0,
      validAnswers: 0,
      invalidAnswers: 0
    };
  }
  @MessagePattern({ cmd: CommandsConsts.RegisterUser})
  async registerUser(@Payload() data: RegisterUserModel) {
    this.logger.verbose(`Register user: Entering`);
    const user = await this.guestService.create({
      ...data,
    });
    delete user.photo;
    this.logger.log(`Created user: ${data.name}, ${data.telegramId}`);
    return user;
  }

  @MessagePattern({ cmd: CommandsConsts.PhotoUpdated })
  async photoUpdated(@Payload() data: { id: number}) {
    this.logger.verbose(`Photo updated event, send notification`);
    this.sharedService.notifyAllClients<{id: number}>(ClientNotificationType.PhotosUpdated, data)
  }

  @MessagePattern({ cmd: CommandsConsts.CardPlayed })
  async cardPlayed(@Payload() data: { user: number, text: string }) {
    this.eventBus.publish(
      new PlayerCardSelectedEvent(data.user, getCard(data.text)),
    );
    return;
  }

  @MessagePattern({ cmd: CommandsConsts.GetQuestion})
  async getQuestion(@Payload() data: { user: number, inline: false}) {
    await this.quizService.displayQuestionForUser(data.user);
  }

}