#include"./EV_const.dnh"

let bgm = ObjSound_Create();
let Current = GetCurrentScriptDirectory();

let songlists = [Current ~ "./../../Bgm/pg_prebattle1.mp3",
                 Current ~ "./../../Bgm/pg_prebattle2.ogg",
				 Current ~ "./../../Bgm/pg_boss1.mp3",
				 Current ~ "./../../Bgm/pg_boss2.ogg",
				 Current ~ "./../../Bgm/pg_boss3.ogg"];
@Initialize
{
SetCommonData("MusicSystem",true);
}

@MainLoop
{
yield;
}

@Event
{
	alternative(GetEventType())
	case(EV_PAUSE_ENTER)
	{
		ObjSound_Stop(bgm);
		ObjSound_SetRestartEnable(bgm,true);
	}
	case(EV_PAUSE_LEAVE)
	{
		ObjSound_Play(bgm);
		ObjSound_SetRestartEnable(bgm,false);
	}
	case(EV_PLAYMUSIC)
	{
	let data = GetEventArgument(0);
	if(!GetCommonData("Menu",false)){
		PlayMusic(songlists[ator(data[0])],ator(data[1]),data[2],data[3]);
		}
	}
	case(EV_STOPMUSIC)
	{
	if(!GetCommonData("Menu",false)){
	ObjSound_Stop(bgm);
	ObjSound_SetLoopEnable(bgm,false);
	}
	}
	case(EV_EXPLODE)
	{
	let data = GetEventArgument(0);
	if(!GetCommonData("Menu",false)){
		MapleExplode(data[0],data[1],data[2],data[3]);
		}
	}
}

task PlayMusic(str,v,loopstart,loopend){
	ObjSound_Load(bgm,str);
	ObjSound_SetSoundDivision(bgm,SOUND_BGM);
	ObjSound_SetVolumeRate(bgm,v);
	ObjSound_SetLoopEnable(bgm,true);
	ObjSound_SetLoopTime(bgm,loopstart,loopend);
	ObjSound_SetRestartEnable(bgm,false);
	ObjSound_Play(bgm);
}

function wait(n){loop(n){yield;}}

task MapleExplode(time,num,min,max){ // task for explode maples
	PlayExpSound(100,0);
	let bosscoor = GetCommonData("BossPos",[0,0]);
	let px = bosscoor[0];
	let py = bosscoor[1];
	ascent(i in 0..time){
	loop(num){
	Explode(px,py,rand(min,max),rand(0,359),rand(1,3));
	}
	wait(i%2);
	}
	}
	
	task Explode(px,py,spd,dir,size){
	let obj=ObjPrim_Create(OBJ_SPRITE_2D);
	let img=GetCurrentScriptDirectory~"./../img/eff2.png";
	let r = 0;
	let angle = rand(0,359);
	let alpha = 255;
	let minus = 256/(size/0.03);
	ObjPrim_SetTexture(obj,img);
	ObjSprite2D_SetSourceRect(obj,32,226,64,254);
	ObjSprite2D_SetDestCenter(obj);
	ObjRender_SetScaleXYZ(obj,size,size,size);
	ObjRender_SetBlendType(obj,BLEND_ADD_ARGB);
	ObjRender_SetAlpha(obj,255);
	while(alpha>0){
	ObjRender_SetPosition(obj,px+r*cos(dir),py+r*sin(dir),0);
	ObjRender_SetScaleXYZ(obj,size,size,size);
	ObjRender_SetAngleXYZ(obj,0,0,angle);
	ObjRender_SetAlpha(obj,alpha);
	alpha -= minus;
	angle += size*1.5;
	r+= spd;
	spd -= 0.02;
	size -= 0.01;
	yield;
	}
	Obj_Delete(obj);
	}
	
task PlayExpSound(v,w){
	let s = ObjSound_Create;
	ObjSound_Load(s,GetMainStgScriptDirectory~"./../sound/enemoff.wav");
	loop(w){yield;}
	ObjSound_SetSoundDivision(s,SOUND_SE);
	ObjSound_SetVolumeRate(s,v);
	ObjSound_Play(s);
	loop(631){yield;}
	
	
	Obj_Delete(s);
}