class SimpleSound {
	static context:AudioContext;
	static bgmSource:AudioBufferSourceNode;
	static bgmGain:GainNode;
	static soundGain:GainNode;
	static getAudioContext() {
		if (SimpleSound.context)
			return SimpleSound.context;
		SimpleSound.context = <AudioContext>SimpleSound._getAudioContext();
		return SimpleSound.context;
	}

	static _getAudioContext() {
		if (window["AudioContext"]) {
			return new window["AudioContext"]();
		} else if (window["webkitAudioContext"]) {
			return new window["webkitAudioContext"]();
		} else {
			return null;
		}
	}

	static play(sound:AudioBuffer, loop?:bool, when?:number, gain?:GainNode) {
		var context = SimpleSound.getAudioContext();
		var bufferSource = context.createBufferSource();
		if (loop)
			bufferSource.loop = true;

		bufferSource.buffer = sound;
		if (gain) {
			bufferSource.connect(gain);
		} else {
			if (! SimpleSound.soundGain) {
				var soundGain = context.createGain();
				soundGain.connect(context.destination);
				SimpleSound.soundGain = soundGain;
			}
			bufferSource.connect(SimpleSound.soundGain);
		}
		bufferSource.start(
			when === undefined ? 0 : when
		);
		return bufferSource;
	}

	static hasBgm() {
		return SimpleSound.bgmSource !== undefined;
	}

	static playBgm(sound:AudioBuffer, loop?:bool, when?:number) {
		if (SimpleSound.bgmSource)
			SimpleSound.stopBgm();

		if (!SimpleSound.bgmGain) {
			var context = SimpleSound.getAudioContext();
			var bgmGain = context.createGain();
			bgmGain.connect(context.destination);
			SimpleSound.bgmGain = bgmGain;
		}
		SimpleSound.bgmSource = SimpleSound.play(sound, loop, when, SimpleSound.bgmGain);
		return SimpleSound.bgmSource;
	}

	static stop(source:AudioBufferSourceNode, when?:number) {
		if (! source)
			return;
		source.stop(when === undefined ? 0 : when);
	}

	static stopBgm(when?:number) {
		SimpleSound.stop(SimpleSound.bgmSource, when);
		delete SimpleSound.bgmSource;
	}

	//test function. copied by tmlib.js https://github.com/phi1618/tmlib.js/
	static tone(hertz, seconds) {
		hertz   = hertz !== undefined ? hertz : 200;
		seconds = seconds !== undefined ? seconds : 1;
		var nChannels   = 1;
		var sampleRate  = 44100;
		var amplitude   = 2;
		var context = SimpleSound.getAudioContext();
		var buffer  = context.createBuffer(nChannels, seconds*sampleRate, sampleRate);
		var fArray  = buffer.getChannelData(0);
		for(var i = 0; i < fArray.length; i++){
			var time    = i / buffer.sampleRate;
			var angle   = hertz * time * Math.PI;
			fArray[i]   = Math.sin(angle)*amplitude;
		}
		return buffer;
	}
}