class AutoLoad {
    constructor(selector, callback, duration) {
        this.$contanier = $(selector)
        this.loading = false
        this.callback = callback
        this.duration = duration || 200
        this._turnOff_ = false
        this._bindEve()
    }
    _bindEve() {
        this._bindThisEve = this._afterScroll.bind(this)
        $(window).on('scroll', this._bindThisEve)
    }

    _offEve() {
        var $win = $(window)
        $win.off('scroll', this._bindThisEve)
    }

    turnOff() {
        this._turnOff_ = true
    }

    turnOn() {
        this._turnOff_ = false
    }

    _afterScroll() {
        if (this.loading || this._turnOff_) return

        var self = this,
            $win = $(window),
            screenHeight = $win.height(),
            offsetBottom = this.$contanier.offset().top + this.$contanier.height()


        if (screenHeight + $win.scrollTop() >= offsetBottom) {
            this.loading = true

            self.callback && self.callback()
        }
    }

    end() {
        this._offEve()
    }

    done() {
        var self = this
        setTimeout(function () {
            self.loading = false
        }, self.duration);
    }
}

module.exports = AutoLoad