import {Injectable, Logger} from '@nestjs/common'; import {Cron} from '@nestjs/schedule'; import {StateService} from '../state/state.service'; import {QuizService} from '../quiz/quiz.service'; import {GiftsService} from '../gifts/gifts.service'; import {SharedService} from '../shared/shared.service'; import {FeatureflagService} from "../featureflag/featureflag.service"; import {FeatureFlagsConsts} from "../Consts/FeatureFlags.consts"; import {CommandBus} from "@nestjs/cqrs"; import {GameStateConsts} from "../Consts/game-state.consts"; import {IStateInfo} from "../Consts/types"; import {ClientNotificationType} from "../socket/socket.gateway"; @Injectable() export class SchedulerService { private readonly logger = new Logger(SchedulerService.name); private state; constructor( private stateService: StateService, private giftsService: GiftsService, private quizService: QuizService, private sharedService: SharedService, private featureFlagService: FeatureflagService, private commandBus: CommandBus, ) {} @Cron('* * * * *') async handleCron() { await this.updateState(); } async finishGame() { if(await this.featureFlagService.getFeatureFlag(FeatureFlagsConsts.EnableEndgamePoints)) { this.logger.verbose(`Feature flag ${FeatureFlagsConsts.EnableEndgamePoints} is enabled`); const endgamePoints = await this.quizService.calculateEndgamePoints(); const state = await this.stateService.setState(GameStateConsts.Main, GameStateConsts.EndgamePoints); this.sharedService.notifyAllClients(ClientNotificationType.StateChanged, state); } else { const state = await this.stateService.setState('main', 'finish'); this.sharedService.notifyAllClients(ClientNotificationType.StateChanged, state); this.logger.warn(`Gifts is ended, finishing game`); } } private async updateState() { this.state = (await this.stateService.getState('main')).value; this.logger.verbose(`Game state is: ${this.state}`); } @Cron('* * * * *') async gameStatus() { const giftsLeft = await this.giftsService.getRemainingPrizeCount(); if (giftsLeft === 0) { await this.finishGame(); } const questionsLeft = await this.quizService.getRemainQuestionCount(); this.logger.verbose( `Gifts left ${giftsLeft}, Questions without answer: ${questionsLeft}`, ); } }