import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from "@angular/common/http";
import { API_URL } from "../../app.constants";
import {delay, delayWhen, interval, Observable, of, Subject} from "rxjs";
import {ApiService} from "./api.service";
import {takeUntil, tap} from "rxjs/operators";
import {SharedMethods} from "../shared/sharedmethods";

@Injectable({
  providedIn: 'root'
})
export class VoiceService {
  destroyed$ = new Subject();
  voiceDisabled = false;

  constructor(private httpClient: HttpClient, private apiService: ApiService) {
    this.apiService.getFeatureFlagState("DisableVoice").pipe(takeUntil(this.destroyed$))
      .subscribe((result) => {
        this.voiceDisabled = result.state;
      })
  }
  public voiceSubject = new Subject<string>();
  public audioEndedSubject = new Subject<void>();

  playAudio(url: string) {
    console.log(`play audio ${url}`);
    this.voiceSubject.next(url);
  }

  playAudio$(url: string) {
    this.voiceSubject.next(url);
    return new Observable((observer) => {
      if(this.voiceDisabled) {
        observer.next(null);
        observer.complete();
      }
      const subscription = this.audioEndedSubject.subscribe({
        next: () => {
          observer.next(null);
          observer.complete();
        }
      });
      return () => subscription.unsubscribe();
    }).pipe(delayWhen(val => this.voiceDisabled ? interval(5000) : interval(0)));
  }

  getAudioUrl(text: string,voice: number = 1) {
    return `${API_URL}/voice/tts?voice=${voice}&text=${text}`
  }

  getAudioUrlSSML(text: string) {
    return `${API_URL}/voice/ssml?text=${encodeURI(text)}`
  }

  audioEnded() {
    this.audioEndedSubject.next();
  }
}
