/*
 * 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'),
            createUrl         = options.createUrl,
            uploadPrototype   = options.uploadPrototype,
            downloadPrototype = options.downloadPrototype;

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

        if(options.acceptFileTypes) {
            options.acceptFileTypes = new RegExp('^' + options.acceptFileTypes + '$');
        }

        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
        $button.fileupload($.extend(
            options,
            {
                type: 'PUT',
                autoUpload: true,
                formData: {},
                multipart: false,
                uploadTemplateId: null,
                downloadTemplateId: null,
                filesContainer: $this.find('.fileinput-entries'),
                uploadTemplate: function(data) {
                    var rows = $();
                    $.each(data.files, function (index, file) {
                        var row = $(uploadPrototype);
                        row.find('.name').text(file.name);
                        row.find('.size').html(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) {
                            if(response.status == 201) {
                                data.url = response.put_url;
                                data.delete_url = response.delete_url;
                                data.delete_type = response.delete_type;
                                data.jqXHR = $this.fileupload('send', data);
                            } else {
                                file.error = response.message || ('Error #' + response.status);
                                data.files.error = true;
                                data.context.find('.error').text(file.error);
                            }
                        }
                    );
                    return false;
                },
                progress: function (e, data) {
                    if(!data.context || e.isDefaultPrevented()) {
                        return;
                    }
                    var percent = data.loaded / data.total * 100,
                        percentText = percent.toFixed(1);
                    data.context.each(function () {
                        $this.find('.progress').show().attr('aria-valuenow', percentText);
                        $this.find('.progress-bar').css('width', percent + '%');
                        $this.find('.progress-text').show().html(percentText + '% ('+formatBitrate(data.bitrate)+')');
                    });
                }
            }
        )).bind({
            fileuploadfailed: function (e, data) {
                if(data.delete_url) {
                    $.ajax(data.delete_url, { type: data.delete_type });
                }
            },
            fileuploadadded: updateButtonVisibility,
            fileuploadfinished: updateButtonVisibility,
            fileuploaddestroyed: updateButtonVisibility,
            fileuploadprocessalways: updateButtonVisibility
        });

        if(options.disabled || options.readonly) {
            $button.fileupload('disable');
        }

    };

})(jQuery);