/*
 * Copyright (C) 2015 IRSTEA
 * All rights reserved.
 */
(function($) {

    /** Plugin irsteaFileUpload.
     */
    $.fn.irsteaFileUpload = function(options) {

        var $this             = $(this),
            $button           = $this.find('.fileinput-button'),
            $entries          = $this.find('.fileinput-entries'),
            prototype         = options.prototype,
            createUrl         = options.createUrl,
            uploadPrototype   = options.uploadPrototype,
            downloadPrototype = options.downloadPrototype;

        delete options.prototype;
        delete options.createUrl;
        delete options.uploadPrototype;
        delete options.downloadPrototype;

        var formatSize = function(size) {
                if(size > 1000000000) {
                    return (size/1000000000).toFixed(2) + ' Gio';
                }
                if(size > 1000000) {
                    return (size/1000000).toFixed(2) + ' Mio';
                }
                if(size > 1000) {
                    return (size/1000).toFixed(2)+ ' Kio';
                }
                return size + ' o';
            },
            formatBitrate = function(rate) {
                return formatSize(rate) + '/s';
            },
            updateButtonVisibility = function() {
                if($entries.children().length > 0 && !options.multiple) {
                    $button.hide();
                } else {
                    $button.show();
                }
            };

        $this.find('.template-download .size').each(function() { $(this).html(formatSize($(this).text())); });

        updateButtonVisibility();

        // Activation
        $this.fileupload($.extend(
            options,
            {
                type: 'PUT',
                autoUpload: true,
                formData: {},
                multipart: false,
                uploadTemplateId: null,
                downloadTemplateId: null,
                filesContainer: $this.find('.fileinput-entries'),
                maxChunkSize: options.maxChunkSize || 1000000,
                uploadTemplate: function(data) {
                    var rows = $();
                    $.each(data.files, function (index, file) {
                        var row = $(uploadPrototype);
                        row.find('.name').text(file.name);
                        row.find('.size').text(formatSize(file.size));
                        if (file.error) {
                            row.find('.error').text(file.error);
                        }
                        rows = rows.add(row);
                    });
                    return rows;
                },
                downloadTemplate: function(data) {
                    var rows = $();
                    $.each(data.files, function (index, file) {
                        var row = $(downloadPrototype);
                        row.find('.size').html(formatSize(file.size));
                        if (file.error) {
                            row.find('.name').text(file.name);
                            row.find('.error').text(file.error);
                        } else {
                            row.find('.name a')
                                .text(file.name)
                                .prop('href', file.url);
                            row.find('button.delete')
                                .attr('data-type', file.delete_type)
                                .attr('data-url', file.delete_url);
                            row.find('input:hidden')
                                .val(file.id);
                        }
                        rows = rows.add(row);
                    });
                    return rows;
                },
                submit: function (e, data) {
                    var $this = $(this),
                        file = data.files[0];
                    $.post(
                        createUrl,
                        { file: { name: file.name, size: file.size, type: file.type, lastModified: file.lastModified } },
                        function(response) {
                            data.url = response.url;
                            data.jqXHR = $this.fileupload('send', data);
                            data.context.find('.progress').show();
                        }
                    );
                    return false;
                },
                progress: function (e, data) {
                    if(!data.context || e.isDefaultPrevented()) {
                        return;
                    }
                    var progress = Math.floor(data.loaded / data.total * 100);
                    data.context.each(function () {
                        $(this).find('.progress')
                            .attr('aria-valuenow', progress)
                            .children().first().css('width',progress + '%');
                        $(this).find('.progress-text').html(progress + '% ('+formatBitrate(data.bitrate)+')');
                    });
                }
            }
        )).bind({
            fileuploadfailed: function (e, data) {
                if(data.url) {
                    $.ajax(data.url, { type: 'DELETE' });
                }
            },
            fileuploadadded: updateButtonVisibility,
            fileuploadfinished: updateButtonVisibility,
            fileuploaddestroyed: updateButtonVisibility
        });

    };

})(jQuery);