import {setEcoInterval} from './utils';
import Model from './model';

export default class Live {
    constructor({url,timeout=10,src=""}={}) {
        this.url = url;
        this.timeout = timeout;
        this.src = src;

        this.interval = null
        this.promise = null
        this.items = []
        this.current = null
    }

    //-- data refreshing
    drop() {
        this.promise = null;
    }

    /**
     * Fetch data from server.
     *
     * @param {Object} options
     * @param {Function} options.then: call this method on fetch, `this` passed as argument.
     * @return {Promise} Promise resolving to fetched items.
     */
    fetch({then=null}={}) {
        const promise = fetch(this.url).then(response =>
            response.ok ? response.json()
                        : Promise.reject(response)
        ).then(data => {
            data.forEach(item => {
                if(item.start) item.start = new Date(item.start)
                if(item.end) item.end = new Date(item.end)
            })
            this.items = data

            const now = new Date()
            let item = data.find(it => it.start && (it.start <= now < it.end)) ||
                       data.length ? data[0] : null;
            if(item) {
                item.src = this.src
                this.current = new Model(item)
            }
            else
                this.current = null
            if(then)
                then(this)
            return this.items
        })

        this.promise = promise;
        return promise;
    }

    _refresh(options={}) {
        const promise = this.fetch(options);
        promise.then(() => {
            if(promise != this.promise)
                return [];
        })
        return promise
    }

    /**
     * Refresh live info every `this.timeout`.
     * @param {Object} options: arguments passed to `this.fetch`.
     */
    refresh(options={}) {
        if(this.interval !== null)
            return

        this._refresh(options)
        this.interval = setEcoInterval(() => this._refresh(options), this.timeout*1000)
        return this.interval
    }

    stopRefresh() {
        this.interval !== null && clearInterval(this.interval)
    }
}
