import {Controller, Get, Header, Logger, NotFoundException, Query, StreamableFile} from '@nestjs/common';
import { VoiceService } from './voice.service';
import { TtsRequestDto, TtsRequestWithVars } from './models/TtsRequestDto';
import { invalidPrefixDict } from './dicts/invalid-prefix.dict';
import { validPrefixDict } from './dicts/valid-prefix.dict';
import * as translit from 'latin-to-cyrillic';
import {FeatureflagService} from "../featureflag/featureflag.service";
import {FeatureFlagsConsts} from "../Consts/FeatureFlags.consts";
@Controller('voice')
export class VoiceController {
  private voiceEnabled = false;
  private logger = new Logger(VoiceController.name)
  constructor(private voiceService: VoiceService,private featureFlagService: FeatureflagService) {
    setInterval(() => {
      this.featureFlagService.getFeatureFlag(FeatureFlagsConsts.DisableVoice).then(r => this.voiceEnabled = !r.state);
    }, 10000);
    this.featureFlagService.getFeatureFlag(FeatureFlagsConsts.DisableVoice).then(r => {
      this.voiceEnabled = !r.state;
    });

  }

  @Get('ssml')
  @Header('content-type', 'audio/opus')
  @Header('content-disposition', 'inline')
  async textToSpeechSSML(@Query() dto: TtsRequestDto) {
    this.logger.verbose(`[textToSpeechSSML] enter, FF state is: ${this.voiceEnabled}`);
    if (this.voiceEnabled) {
      return new StreamableFile(await this.voiceService.textToFile(dto, true));
    } else {
      return new NotFoundException('Voice disabled');
    }
  }

  @Get('tts')
  @Header('content-type', 'audio/opus')
  @Header('content-disposition', 'inline')
  async getText(@Query() dto: TtsRequestDto) {
    dto.text = translit(dto.text);
    if (this.voiceEnabled)  {
      return new StreamableFile(await this.voiceService.textToFile(dto));
    } else {
      return new NotFoundException('Voice disabled');
    }
  }
  @Get('announce-valid')
  @Header('content-type', 'audio/opus')
  @Header('content-disposition', 'inline')
  async announceValid(@Query() dto: TtsRequestWithVars) {
    if (this.voiceEnabled) {
      const vars = JSON.parse(dto.vars);
      dto.text = this.voiceService.buildTemplate(dto, vars, validPrefixDict);
      return new StreamableFile(await this.voiceService.textToFile(dto));
    } else {
      return new NotFoundException('Voice disabled');
    }
  }

  @Get('announce-invalid')
  @Header('content-type', 'audio/opus')
  @Header('content-disposition', 'inline')
  async announceInvalid(@Query() dto: TtsRequestWithVars) {
    if (this.voiceEnabled) {
      const vars = JSON.parse(dto.vars);
      dto.text = this.voiceService.buildTemplate(dto, vars, invalidPrefixDict);
      return new StreamableFile(await this.voiceService.textToFile(dto));
    } else {
      return new NotFoundException('Voice disabled');
    }
  }
}
