"use strict";

var GO_MusicSwitcher = function(w,h,bgmName,loop,immediate){
	this.sprite = new Sprite(null,"MusicSwitcher");
	this.sprite.collision_flags = 
		DEFINE_SPRITE_COLLISION_FLAGS.SPRITES_PASSIVE;
	this.sprite.setBoundingBox(0,0,(w!==null)?parseInt(w):15,(h!==null)?parseInt(h):15);
	this.sprite.game_object = this; // no longer a generic GO
	
	this.bgm_name = bgmName; // what to switch to
	this.loop = loop; // loop the new tune
	this.immediate = immediate; // true = start immediately when triggered; false = wait for current BGM to flag as has_looped
	this.triggered = false;
	this.switched = false;
	this.auto = false;
	if (w==0 || h==0){
		this.interactions = 0;
		this.auto = true;
	}
};

GO_MusicSwitcher.prototype = new GameObject(
	new Sprite(
		null,
		"MusicSwitcher"
	),
	"MusicSwitcher"
	);

	GO_MusicSwitcher.prototype.interactions = 
		DEFINE_GAMEOBJECT_INTERACTIONS.TRIGGER;

	GO_MusicSwitcher.prototype.Update = function(){
		// if we have no trigger zone, trigger immediately on Update.
		// would trigger on Load, except room's default BGM probably isn't set up
		if (this.auto && !this.triggered){
			this.triggerEvent();
		}

		if (this.triggered && !this.immediate && !this.switched && SDS.bgm && SDS.bgm.has_looped){
			this.switchBgm();
		}

	};

	GO_MusicSwitcher.prototype.triggerEvent = function(){
		if (!this.triggered && SDS.bgm.name!==this.bgm_name){
			if (this.immediate){
				this.switchBgm();
			}
			else if (SDS.bgm){
				SDS.bgm.has_looped = false;
			}
		}

		this.interactions = 0;
		this.triggered = true;
		return null;
	};

	GO_MusicSwitcher.prototype.switchBgm = function(){
		if (SDS.bgm_name!==this.bgm_name){
			SDS.switchBgm(this.bgm_name,this.loop);
		}
		this.switched = true;
	};
