import { NotificationStore } from 'lib2/stores';

const DEFAULT_TTL = 7000;

class Notification {
    constructor(props) {
        this.id = Math.random().toString(36).slice(2);
        this.ttl = DEFAULT_TTL;

        Object.assign(this, props);

        if (typeof this.ttl === 'number') {
            setTimeout(() => this.remove(), this.ttl);
        }

        this.enqueue();
    }
    enqueue() {
        let queue = NotificationStore.get('queue') || [];

        queue.push(this);

        NotificationStore.set('queue', queue);
    }
    remove() {
        let queue = NotificationStore.get('queue');

        if (queue) {
            let updatedQueue = queue.filter(({ id }) => id !== this.id);

            if (updatedQueue.length !== queue.length) {
                NotificationStore.set('queue', updatedQueue);
            }
        }
    }
}

// options.ttl: null, 'forever' или любое нечисловое значение для вечноживущей нотификации
function notify(message, type = 'success', options = {}) {
    return new Notification({ message, type, ...options });
}

export default window.ya.connect.notify = notify;
