import EventTarget from './EventTarget';

const whenFilled = function(successCallback) {
    if (successCallback && typeof successCallback === 'function') {
        this._filledCallbacks.push({ once: false, callback: successCallback });
    }

    if (this._value) {
        successCallback(this._value);
    }
};

const whenNext = function(callback) {
    if (callback && typeof callback === 'function') {
        this._filledCallbacks.push({ once: true, callback: callback });
    }
}

const once = function(callback) {
    if (callback && typeof callback === 'function') {
        if (!this._value) {
            this._filledCallbacks.push({ once: true, callback: callback });
        } else {
            callback(this._value);
        }
    }
};

// fake then if this should be handed to something that expects a promise
whenFilled.then = whenNext.then = once.then = function(...args) {
    this(...args);
};

// dummy catch incase someone tries to use it
whenFilled.catch = whenNext.then = once.then = function() {};

const DataStorage = {
    _value: null,
    _filledCallbacks: [],

    get value() {
        return this._value;
    },

    constructor() {
        this.whenFilled = whenFilled.bind(this);
        this.whenNext = whenNext.bind(this);
        this.once = once.bind(this);
        this._filledCallbacks = [];
    },

    fill(value) {
        this._value = value;

        this._filledCallbacks = this._filledCallbacks.filter(item => {
            item.callback(this._value);
            return !item.once;
        });
    },

    when: null,

    once: null,

    whenNext: null,

    __proto__: EventTarget,
};

export default DataStorage;

@@ -182,25 +182,25 @@
 backs.push(%7B
-%C2%A0
+ 
 once: false,
@@ -479,16 +479,17 @@
 %0A    %7D%0A%7D
+;
 %0A%0Aconst 
@@ -642,9 +642,9 @@
 sh(%7B
-%C2%A0
+ 
 once
@@ -879,35 +879,97 @@
 ion(
-...args)
+callback) %7B%0A    return (new Promise((done) =%3E
  %7B%0A    
+ 
+   
 this(
-...args
+done);%0A    %7D)).then(callback
 );%0A%7D
@@ -988,16 +988,17 @@
 catch in
+ 
 case som
@@ -1042,36 +1042,37 @@
  = whenNext.
-then
+catch
  = once.
 then = funct
@@ -1051,36 +1051,37 @@
 xt.catch = once.
-then
+catch
  = function() %7B%7D
@@ -1076,19 +1076,109 @@
 unction(
-) %7B
+callback) %7B%0A    return (new Promise((done) =%3E %7B%0A        this(done);%0A    %7D)).catch(callback);%0A
 %7D;%0A%0Acons
@@ -1331,22 +1331,16 @@
 his.when
-Filled
  = whenF
@@ -1474,16 +1474,38 @@
 ks = %5B%5D;
+%0A%0A        return this;
 %0A    %7D,%0A

fix DataStorage