// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['jquery'], function() {
    (function($) {
        // jQuery plugin definition
        $.fn.hpProgressBar = function(options) {
          
            function hpProgressBar(elem) {
              
                var container;
                var done;
                
                function update(percentDone) {
                    container.toggleClass('hp-skipped', percentDone < 0);
                    if (percentDone > 100) {
                        percentDone = 100;
                    } else if (percentDone < 0) {
                        percentDone = 0;
                    }
                    container.toggleClass('hp-finished', 100 === percentDone);
                    done.css('width', percentDone + '%');
                }
                
                function build() {
                    container.addClass('hp-progress');
                    done = $('.hp-progress-done', container);
                    if (done.length === 0) {
                        container.append($('<div class="hp-progress-done"></div>'));
                        done = $('.hp-progress-done', container).css('width', '0px');
                    }
                }

                function initialize() {
                    container = $(elem);
                    build();
                    // allow options to be 0
                    if (null !== options && undefined !== options &&
                        'number' === typeof(options)) {
                        update(options);
                    } else if (container.attr('data-percent')) {
                        update(container.attr('data-percent'));
                    }
                }
                
                initialize();
            }
            
            // pluginify
            var ret;
            var instance = null;
            this.each(function() {
                var $elem = $(this);
                instance = new hpProgressBar($elem[0]);
                ret = ret ? ret.add($elem) : $elem;
            });
            return ret;
        };
    }(jQuery));
});
