import { DEFAULT_GAME_AUDIO_CONFIG, type AudioCueKey, type GameAudioConfig } from '../audio/audioConfig'
import { SoundDirector } from '../audio/soundDirector'
import { type GameEffect } from '../core/gameResult'
import { type AnimationLevel } from '../../utils/animationLevel'
import {
  DEFAULT_GAME_HAPTICS_CONFIG,
  DEFAULT_GAME_UI_EFFECTS_CONFIG,
  type FeedbackCueKey,
  type GameHapticsConfig,
  type GameUiEffectsConfig,
} from './feedbackConfig'
import { HapticsDirector } from './hapticsDirector'
import { UiEffectDirector, type UiEffectHost } from './uiEffectDirector'

export interface FeedbackHost extends UiEffectHost {
  stopLocationTracking: () => void
}

export interface FeedbackConfigBundle {
  audioConfig?: GameAudioConfig
  hapticsConfig?: GameHapticsConfig
  uiEffectsConfig?: GameUiEffectsConfig
}

export class FeedbackDirector {
  soundDirector: SoundDirector
  hapticsDirector: HapticsDirector
  uiEffectDirector: UiEffectDirector
  host: FeedbackHost

  constructor(host: FeedbackHost, config?: FeedbackConfigBundle) {
    this.host = host
    this.soundDirector = new SoundDirector(config && config.audioConfig ? config.audioConfig : DEFAULT_GAME_AUDIO_CONFIG)
    this.hapticsDirector = new HapticsDirector(config && config.hapticsConfig ? config.hapticsConfig : DEFAULT_GAME_HAPTICS_CONFIG)
    this.uiEffectDirector = new UiEffectDirector(host, config && config.uiEffectsConfig ? config.uiEffectsConfig : DEFAULT_GAME_UI_EFFECTS_CONFIG)
  }

  configure(config: FeedbackConfigBundle): void {
    this.soundDirector.configure(config.audioConfig || DEFAULT_GAME_AUDIO_CONFIG)
    this.hapticsDirector.configure(config.hapticsConfig || DEFAULT_GAME_HAPTICS_CONFIG)
    this.uiEffectDirector.configure(config.uiEffectsConfig || DEFAULT_GAME_UI_EFFECTS_CONFIG)
  }

  reset(): void {
    this.soundDirector.resetContexts()
    this.uiEffectDirector.clearPunchButtonMotion()
    this.uiEffectDirector.clearHudProgressMotion()
    this.uiEffectDirector.clearHudDistanceMotion()
  }

  destroy(): void {
    this.soundDirector.destroy()
    this.hapticsDirector.destroy()
    this.uiEffectDirector.destroy()
  }

  setAnimationLevel(level: AnimationLevel): void {
    this.uiEffectDirector.setAnimationLevel(level)
  }

  setAppAudioMode(mode: 'foreground' | 'background'): void {
    this.soundDirector.setAppAudioMode(mode)
  }

  playAudioCue(key: AudioCueKey): void {
    this.soundDirector.play(key)
  }

  playHapticCue(key: FeedbackCueKey): void {
    this.hapticsDirector.trigger(key)
  }

  handleEffects(effects: GameEffect[]): void {
    this.soundDirector.handleEffects(effects)
    this.hapticsDirector.handleEffects(effects)
    this.uiEffectDirector.handleEffects(effects)

    if (effects.some((effect) => effect.type === 'session_finished' || effect.type === 'session_timed_out')) {
      this.host.stopLocationTracking()
    }
  }
}
