extends GameExtender

const manager = preload("res://Modules/FoxLib/Internal/FoxLibAudioManager.gd")
const Globals = preload("res://FoxLib/Globals.gd")
const Doll = preload("res://Player/Player3D/Doll3D.gd")

var Smod = GlobalRegistry.getModule("SoundModule")
var wasScene
var inSexEngine:bool
var pack
var playedThisUpdate = false
var variance = Smod.pitchVarianceOption
var sfxPlayer2:AudioStreamPlayer

#var allactivities:Dictionary = GlobalRegistry.getSexActivityReferences()

var background = {
	"DomPutBreastPumpOnSub":"sextoy",
	"DomPutPenisPumpOnSub":"sextoy",
	"DomRidingSubAnal":"plaps",
	"DomRidingSubVaginal":"plaps",
	"SexVaginalOnAllFours":"plaps",
	"SexAnalOnAllFours":"plaps",
	"ThreeDDS_DP":"plaps2",
	"ThreeDDS_SpitroastAnal":"plaps2",
	"ThreeDDS_SpitroastVag":"plaps2",
	"ThreeDDS_Train":"plaps",
	"ThreeDSS_Buttstack":"plaps",
	"SixtyNine":"oral",
	"SexOral":"oral",
	"DomOralSexOnSub":"oral",
	"SexPawjobMutual":"handjob",
	"SexPawjob":"handjob",
	"Tribadism":"grind",
	
}

var oneshot = {
	"DomBondage":"chain",
	"DomLeashesSub":"chain",
	"Spanking":"spank",
	"BeatingUpWhenAngry":"slap",
	"DomUndressActions":"clothes",
	"DomUndressesSub":"clothes",
	"SubUndressActions":"clothes",
}

func _init():
	id = "EnginePlayer"
	# does nothing for now
	# might be used to trigger sounds based on current sexActivity
	
func register(_GES:GameExtenderSystem):
#	_GES.register(self, ExtendGame.pcUpdateNonBattleEffects)
	_GES.register(self,ExtendGame.pcUpdateNonBattleEffects) 

func pcUpdateNonBattleEffects(_pc:Player):
	playedThisUpdate = false
	var test:SexActivityBase
	var currentScene = FoxUIManager.getCurrentScene()
	sfxPlayer2 = AudioStreamPlayer.new()
	currentScene.add_child(sfxPlayer2)
#	yield(GM.main, "saveLoadingFinished")
	if(GM.main.sceneStack.size() > 0): #wait until the game is loaded
		wasScene = GM.main.getCurrentScene() #need this to detect some exceptions
		
	if(wasScene.sceneID == "GenericSexScene"):
		if(wasScene.sexEngine.isInvolved("pc")):
			var engine:SexEngine = wasScene.sexEngine
			var activity = engine.currentLastActivityID
			test = engine.getActivityWithUniqueID(activity-1)
			var peeps = engine.getCharIDList()
			for pers in peeps:
				var _temp = engine.getCharInfo(pers)
				yield(wasScene.get_tree().create_timer(0.5),"timeout")
				if(pers != "pc" and _temp.didJustCame()):
					cum(GM.main.getCharacter(pers))
					yield(wasScene.get_tree().create_timer(1),"timeout")
					cum(GM.main.getCharacter(pers))
					yield(wasScene.get_tree().create_timer(1.2),"timeout")
					cum(GM.main.getCharacter(pers))
			if(test == null):
				return
			elif(oneshot.keys().has(test.id)):
				var _to_play = oneshot[test.id]
				Log.print("[SoundMod] load sound " + _to_play + " for " + test.id)
				play_effect(engine, _to_play)

		else:
			return
			
	if(GM.pc.hasEffect(StatusEffect.UnderHypnosis) or GM.pc.hasEffect(StatusEffect.HypnoVisorActive)):
		manager.playNamedBGM("SoundModule:Effecthum")
	if(not (GM.pc.hasEffect(StatusEffect.UnderHypnosis) or GM.pc.hasEffect(StatusEffect.HypnoVisorActive))):
		manager.playBGM(null)
					

func playCh2(audioSample, pitchDiff=0.0):
	if audioSample != null and ((audioSample is AudioStreamOGGVorbis) or (audioSample is AudioStreamMP3)) and audioSample.loop:
		# Disable looping for incomming audio samples as we do not support looping audio properly.
		audioSample.loop = false
	if pitchDiff < -0.5:
		pitchDiff = -0.5
	elif pitchDiff > 0.5:
		pitchDiff = 0.5
	if sfxPlayer2.is_playing():
		sfxPlayer2.stop()
	if audioSample != null:
		sfxPlayer2.pitch_scale = 1.0 + pitchDiff
		sfxPlayer2.set_stream(audioSample)
		sfxPlayer2.play()
	else:
		sfxPlayer2.pitch_scale = 1.0

func play_effect(_engine:SexEngine, _activity):
	var sound
	sound = manager.getFoxAudio("SoundModule:Effect"+_activity)
	if sound == null: 
		Log.printerr("[SoundMod] Failed to locate FoxAudio SoundModule: " + pack)
	else:
		playCh2(sound.getLoadedAudio(),variance)
		playedThisUpdate = true
		Log.print("[SoundMod] Playing Audio Object: " + sound.getId())
			
			
func cum(_ch):
	var sound = manager.getFoxAudio("SoundModule:Effectcum")
	if(_ch.hasBodypart(BodypartSlot.Vagina) and not _ch.hasBodypart(BodypartSlot.Penis)):
		sound = manager.getFoxAudio("SoundModule:Effectsquirt")
	if sound == null:
		Log.printerr("[SoundMod] Failed to locate FoxAudio SoundModule: " + pack)
	else:
		playCh2(sound.getLoadedAudio(),variance)
		playedThisUpdate = true
			
			

#	var doms = _engine.getDoms().keys()
#	var subs = _engine.getSubs().keys()
#	var dom_tags = []
#	var sub_tags = []
#	var tags = []
#
#	for chID in doms:
#		for ii in range(15):
#			if(_engine.hasTag(chID, ii)):
#				dom_tags.append(ii)
#				tags.append(ii)
#
#	for chID in subs:
#		for ii in range(15):
#			if(_engine.hasTag(chID, ii)):
#				sub_tags.append(ii)
#				tags.append(ii)
		
#	if(_activity == "plaps" and tags.has(4) and (tags.has(11) or tags.has(12)) ):
#		sound = manager.getFoxAudio("SoundModule:Effect"+_activity)
#		if sound == null: 
#			Log.printerr("[SoundMod] Failed to locate FoxAudio SoundModule: " + pack)
#		else:
#			sound.setPitchVariance(variance)
#			sound.playAsBGM()
#			Log.print("[SoundMod] Playing Audio Object: " + sound.getId())
#
#	if(_activity == "oral" and tags.has(5)):
#		sound = manager.getFoxAudio("SoundModule:Effect"+_activity)
#		if sound == null: 
#			Log.printerr("[SoundMod] Failed to locate FoxAudio SoundModule: " + pack)
#		else:
#			sound.setPitchVariance(variance)
#			sound.playAsBGM()
#			Log.print("[SoundMod] Playing Audio Object: " + sound.getId())
#
#	if(_activity == "handjob" and sub_tags.has(3)):
#		sound = manager.getFoxAudio("SoundModule:Effect"+_activity)
#		if sound == null: 
#			Log.printerr("[SoundMod] Failed to locate FoxAudio SoundModule: " + pack)
#		else:
#			sound.setPitchVariance(variance)
#			sound.playAsBGM()
#		Log.print("[SoundMod] Playing Audio Object: " + sound.getId())
#
#	if(_activity == "grind" and tags.has(1)):
#		sound = manager.getFoxAudio("SoundModule:Effect"+_activity)
#		if sound == null: 
#			Log.printerr("[SoundMod] Failed to locate FoxAudio SoundModule: " + pack)
#		else:
#			sound.setPitchVariance(variance)
#			sound.playAsBGM()
#		Log.print("[SoundMod] Playing Audio Object: " + sound.getId())

#			sound2.playAsBGM()
#			yield(wasScene.get_tree().create_timer(2),"timeout")
#			manager.stopBGM()



