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";

@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,
  ) {}

  @Cron('* * * * *')
  async handleCron() {
    await this.updateState();
  }

  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) {
      if(await this.featureFlagService.getFeatureFlag(FeatureFlagsConsts.EnableEndgamePoints)) {
        this.logger.verbose(`Feature flag ${FeatureFlagsConsts.EnableEndgamePoints} is enabled`);
      }
      const state = await this.stateService.setState('main', 'finish');
      this.sharedService.sendSocketNotificationToAllClients(
        'state_changed',
        state,
      );
      this.logger.warn(`Gifts is ended, finishing game`);
    }
    const questionsLeft = await this.quizService.getRemainQuestionCount();
    this.logger.verbose(
      `Gifts left ${giftsLeft}, Questions without answer: ${questionsLeft}`,
    );
  }
}
