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

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

    const Slideshow = function( elem ) {
        Widget.call(this, elem);
        this.name = "Slideshow";

        this.id = this.getData('id', '');

        this.nextImage = 0;
        this.updatePending = 0;
        this.imageCount = 0;
        this.needsResize = true;
        this.hovering = false;
        this.paused = false;
        this.toggle = 0;

        this.imageList = [];

        // this.debugLevel = 9;

        $(elem).addClass("widget-slideshow");
    };

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

    Slideshow.prototype.start = function() {
        // Force an update to start, then resize/reposition.
        $(this.elem).html('<img id="0" src="" /><img id="1" src="" /><div class="controls"><div class="control entypo-fast-backward" id="back">&nbsp;</div><div class="control entypo-pause" id="pause">&nbsp;</div><div class="control entypo-fast-forward" id="fwd">&nbsp;</div></div><div class="overlay"></div>');

        $('img#1', this.elem).css( 'display', 'none' );

        // ??? Use of deprecated?
        const self = this;
        $('img#0', this.elem).load( function() { self.scale( $(this) ); } );

        $(this.elem).mouseenter( function() { self.hovering = true; } );
        $(this.elem).mouseleave( function() { self.hovering = false; } );

        $('div.control#pause', this.elem).click( function( e ) {
            self.paused = ! self.paused;
            if ( self.paused ) {
                $(this).removeClass('entypo-pause');
                $(this).addClass('entypo-play');
            } else {
                $(this).removeClass('entypo-play');
                $(this).addClass('entypo-pause');
            }
            e.preventDefault(); e.stopPropagation();
            return false;
        });
        $('div.control#back', this.elem).click( function( e ) {
            self.paused = true;
            $('div.control#pause', $(this).parent()).removeClass('entypo-pause').addClass('entypo-play');
            self.nextImage -= 2;
            if (self.nextImage < 0) self.nextImage = self.imageList.length - 1;
            e.preventDefault(); e.stopPropagation();
            setTimeout( function() { self.update( true ); } );
            return false;
        });
        $('div.control#fwd', this.elem).click( function( e ) {
            self.paused = true;
            $('div.control#pause', $(this).parent()).removeClass('entypo-pause').addClass('entypo-play');
            // ++self.nextImage;
            e.preventDefault(); e.stopPropagation();
            setTimeout( function() { self.update( true ); } );
            return false;
        });

        this.update();

        const interval = this.getData('delay', '5');
        setInterval( function() { self.update(); }, interval * 1000 );
    };

    Slideshow.prototype.update = function( force ) {
        if (typeof force == "undefined") force = false;

        if ( !force && ( this.hovering || this.paused ) ) return;

        // If another process is fetching an image (long-running?) skip this
        if ( this.updatePending++ ) return;

        const self = this;
        if ( force || this.imageList.length == 0 ) {
            // Fetch image list from server
            $.getJSON("ajax/fetchimage.php", { "id" : this.id },
                function( data, status ) {
                    // self.log.debug( 4, 'server says there are ' + data.length + ' images' );
                    self.imageList = [];
                    Array.prototype.push.apply( self.imageList, data );
                    // self.log.debug( 4, 'imageList is now ' + self.imageList.length );
                    this.toggle = 0;
                    this.nextImage = 0;
                }
            );
        }

        let ovl;
        if ( this.imageList.length > 0 ) {
            // Turn on waiting image (it should be loaded by now)
            let img = $('img#0', this.elem);
            img.height(1); img.width(1);
            img.attr('src', 'ajax/fetchimage.php?id=' + this.id + "&fn=" + this.imageList[this.nextImage] );
            // this.scale( img, img.get(0).naturalWidth, img.get(0).naturalHeight );
            img.css( 'display', 'initial' );

            ovl = this.imageList[this.nextImage] + " (" + (this.nextImage+1) + "/" + this.imageList.length + ")";

            // Load next image (hidden)
            ++this.nextImage;
            if ( this.nextImage >= this.imageList.length ) this.nextImage = 0;
            img = $('img#1', this.elem);
            img.css( 'display', 'none' );
            img.attr( 'src', 'ajax/fetchimage.php?id=' + this.id + '&fn=' + this.imageList[this.nextImage] );
        } else
            ovl = "Loading slideshow...";
        $('.overlay', this.elem).text(  ovl );

        this.updatePending = 0;
    };

    Slideshow.prototype.click = function() {
        this.update( true );
    };

    /* Called when gridster finishes resizing a widget */
    Slideshow.prototype.scale = function( elImage ) {
        // Scale the image to preserve the original aspect ratio
        const wid = elImage.get(0).naturalWidth;
        const hgt = elImage.get(0).naturalHeight;
        if ( wid == 0 || hgt == 0 ) return;
        this.log.debug(4, " scale from " + wid + "x" + hgt);
        const widgetX = $(this.elem).parent().get(0).scrollWidth;
        const widgetY = $(this.elem).parent().get(0).scrollHeight;
        let asp = widgetX / wid;
        let newX = Math.floor(wid * asp);
        let newY = Math.floor(hgt * asp);
        if (newY > widgetY) {
            asp = widgetY / hgt;
            newX = Math.floor(wid * asp);
            newY = Math.floor(hgt * asp);
        }
        this.log.debug(4, 'new size is ' + newX + "x" + newY);
        elImage.height( newY );
        elImage.width( newX );
        elImage.attr( 'width', newX );
        elImage.attr( 'height', newY );
    };

    return Slideshow;

}); // define
