//# sourceURL=widgets/KnobWidget.js
/**
 * $Id: KnobWidget.js 282 2018-03-02 23:54:32Z patrick $
 */
/* globals define */

/* TO-DO: Allow min and max to be passed in.
          All of this is old implementation that hasn't been updated completed.
*/

define( [ 'Widget' ], function( Widget ) {

    const KnobWidget = function( elem ) {
        Widget.call( this, elem );
        this.name = "Knob";
        this.lastVal = 0;
        this.animStep = 1;
        this.seekVal = 100;

        $(this.elem).addClass("widget-knob");
        $(this.elem).data('updateMessage', '');
    };

    KnobWidget.prototype = Object.create(Widget.prototype);
    KnobWidget.prototype.constructor = KnobWidget;

    KnobWidget.prototype.messageNotify = function( msg ) {
        // We ignore message because we only register for one
        var val = msg.value;
        $( this.elem ).data( 'updateMessage', "Last updated " + new Date().toLocaleTimeString() );
        if ( val < 0 ) val = 0;
        if ( val > 100 ) val = 100;
        if ( val != this.seekVal ) {
            $( this.elem ).data( this.bindSource, val);
            this.animStep = (val > this.lastVal ? 1 : -1) * 1;
            this.update();
        }
    };

    KnobWidget.prototype.update = function() {
        Widget.prototype.update.call( this );
        this.seek();
    };

    KnobWidget.prototype.seek = function() {
        var self = this;
        var seekVal = $(this.elem).data( this.bindSource );
        if ( this.lastVal != seekVal ) {
            this.lastVal += this.animStep;
            if ( this.animStep > 0 ) {
                if (this.lastVal > seekVal) this.lastVal = seekVal;
            } else if ( this.lastVal < seekVal ) this.lastVal = seekVal;
            // console.log('seek to ' + this.lastVal + ', goal ' + seekVal + ' by ' + this.animStep);
            $('input', this.elem).val(this.lastVal).trigger('change');
            setTimeout( function() { self.update(); } );
        }
    };

    return KnobWidget;

}); // define
