/* globals DDPCommon, EV */

class RadioStation extends EV {
	constructor() {
		super();

		this.instances = {};

		Meteor.connection._stream.on('message', (raw_msg) => {
			const msg = DDPCommon.parseDDP(raw_msg);
			if (msg && msg.msg === 'changed' && msg.collection && msg.fields && msg.fields.eventName && msg.fields.args) {
				// console.log(raw_msg);
				msg.fields.args.unshift(msg.fields.eventName);
				msg.fields.args.unshift(msg.collection);
				this.emit.apply(this, msg.fields.args);
			}
		});
	}
}

Meteor.RadioStation = new RadioStation;


Meteor.Radio = class Radio extends EV {
	constructor(name, {useCollection} = {useCollection: false}) {
		if (Meteor.RadioStation.instances[name]) {
			console.warn('Radio instance already exists:', name);
			return Meteor.RadioStation.instances[name];
		}

		super();

		Meteor.RadioStation.instances[name] = this;

		this.name = name;
		this.useCollection = useCollection;
		this.subscriptions = {};

		Meteor.RadioStation.on(this.subscriptionName, (...args) => {
			if (this.subscriptions[args[0]]) {
				super.emit.apply(this, args);
			}
		});
	}

	get subscriptionName() {
		return `stream-${this.name}`;
	}

	unsubscribe(eventName) {
		delete this.subscriptions[eventName];
	}

	subscribe(eventName) {
		return Meteor.subscribe(this.subscriptionName, eventName, this.useCollection, {
			onStop: () => {
				this.unsubscribe(eventName);
			}
		});
	}

	once(eventName, callback) {
		if (!this.subscriptions[eventName]) {
			this.subscriptions[eventName] = {
				subscription: this.subscribe(eventName)
			};
		}

		super(eventName, callback);
	}

	on(eventName, callback) {
		if (!this.subscriptions[eventName]) {
			this.subscriptions[eventName] = {
				subscription: this.subscribe(eventName)
			};
		}

		super(eventName, callback);
	}

	emit(...args) {
		Meteor.call(this.subscriptionName, ...args);
	}
};

@@ -1001,16 +1001,27 @@
 nName, (
+eventName, 
 ...args)
@@ -1056,19 +1056,75 @@
 ons%5B
-args%5B0%5D%5D) %7B
+eventName%5D) %7B%0A%09%09%09%09this.subscriptions%5BeventName%5D.lastMessage = args;
 %0A%09%09%09
@@ -1135,28 +1135,41 @@
 er.emit.
-apply
+call
 (this, 
+eventName, ...
 args);%0A%09
@@ -1469,32 +1469,32 @@
 ventName);%0A%09%09%09%7D%0A
-
 %09%09%7D);%0A%09%7D%0A%0A%09once(
@@ -1487,16 +1487,202 @@
 %7D);%0A%09%7D%0A%0A
+%09getLastMessageFromEvent(eventName) %7B%0A%09%09const subscription = this.subscriptions%5BeventName%5D;%0A%09%09if (subscription && subscription.lastMessage) %7B%0A%09%09%09return subscription.lastMessage;%0A%09%09%7D%0A%09%7D%0A%0A
 %09once(ev

Save last message from each event and add method to get