/*jshint sub: true */
// UMD pattern
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery', 'fileuploader'], factory);
    } else if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory(require('jquery', 'fileuploader'));
    } else {
        // Browser globals (root is window)
        root.fuu = factory(root.jQuery, root.qq);
    }
}(this, function (jQuery, qq) {

//////////// actual code starts here ///////////////

var fuu = function (options, context, is_angular) {
    this.options = options;
    this.context = context !== undefined ? context : '';

    this.el = jQuery('#' + this.context + 'dropbox_dialog');
    this.files_el = jQuery('.dd_selected_files', this.el);
    this.form_el_name = (this.options['name'] !== undefined ? this.options['name'] : this.context + 'selected_files');

    this.allow_multiple_files = this.options['multiple'];
    this.state = 'idle';

    this.is_angular = is_angular === true;

    this.Init();
};


fuu.prototype.Init = function () {
    this.files_el.on('click', '.dd_delete_file_link',
        jQuery.proxy(function (event) {
            jQuery(event.currentTarget).tooltip('hide');
            var file_key;
            file_key = jQuery(event.currentTarget).siblings('input').val();
            this._removeFile(file_key);
            return false;
        }, this));

    if (!this.is_angular)
    {
	    jQuery('.dd_browse_uploaded_button', this.el).on('click', jQuery.proxy(function (event) {
		    event.preventDefault();
		    this._openSelectModalWindow();
	    }, this));
    }

    jQuery('.dd_extract_archive_btn', this.el).on('click', jQuery.proxy(function (event) {
        event.preventDefault();
        this._unpackArchive();
    }, this));

    /*jshint sub: true */
    var preselected_files = this.options['files'];

    for (var i = 0; i < preselected_files.length; i++) {
        this._addFile(preselected_files[i].file_key, preselected_files[i].file_name);
    }

    this._createFileUploader();
    this._triggerReadyEvent();
};

fuu.prototype.GetState = function () {
    return this.state;
};

fuu.prototype.GetFiles = function () {
    var files = [];
    jQuery('input', this.files_el).each(function (index, el) {
        files[files.length] = {file_name: el.getAttribute('data-filename'), file_key: el.getAttribute('value')};
    });
    return files;
};

fuu.prototype.GetQueueSize = function () {
    return this.ajax_uploader.getInProgress();
};

fuu.prototype.IsMultipleFilesUploaded = function () {
    return jQuery('input', this.files_el).length > 1;
};

// show or hide "unpack archive" checkbox depending on selected files
fuu.prototype._showHideArchiveCheckbox = function () {
    var show_unzip = false;
    if (this.allow_multiple_files) {
        var _this = this;
        jQuery('input', this.files_el).each(function (index, el) {
            if (_this._isArchive(el.getAttribute('data-filename')))
                show_unzip = true;
        });
    }
    jQuery('.dd_extract_archive_div', this.el).toggle(show_unzip);
};

fuu.prototype._unpackArchive = function () {
    if (this.allow_multiple_files) {
        var _this = this;
        jQuery('input', this.files_el).each(function (index, el) {
            if (_this._isArchive(el.getAttribute('data-filename'))) {
                _this._startUnpacking(el)
            }
        });
    }
};

fuu.prototype._startUnpacking = function (el) {
    var file_key = (el.getAttribute('value'));
    console.log(file_key, "/intranet/rest/documents/dropbox/" + file_key + '/unpack');
    var _this = this;
    var li = jQuery(el).closest('li');
	li.find('.qq-upload-spinner, .dd-unpack-failed-text').detach();
    li.append('<span class="qq-upload-spinner"></span>');
    jQuery.ajax({
        url: "/intranet/rest/documents/dropbox/" + file_key + '/unpack',
        method: "POST",
        success: function (data) {
            li.find('.qq-upload-spinner').detach();
            if (data.success) {
                for (var i = 0; i < data.files.length; i++) {
                    var file = data.files[i];
                    _this._addFileQuiet(file.file_key, file.file_name);
                }
                _this._removeFile(file_key);
            } else {
                li.append('<span class="dd-unpack-failed-text">Failed</span>');
            }
        },
        error: function (xhr) {
	        li.find('.qq-upload-spinner').detach();
            li.append('<span class="dd-unpack-failed-text">' + xhr.responseText + '</span>');
        }
    });
};

fuu.prototype._addFileQuiet = function (file_key, file_name) {
    if (!this.allow_multiple_files)
        this.files_el.empty();

    var escaped_file_name = jQuery('<div/>').text(file_name).html();
    var file_line = jQuery('<li class="d-flex">' + escaped_file_name +
        ' <a href="#" class="dd_delete_file_link" rel="tooltip" title="' + lmsg('common.dropbox.remove') + '" data-placement="right"><ion-icon name="trash-outline"></ion-icon></a> ' +
        ' <input type="hidden" name="' + this.form_el_name + '[]" value="' + file_key + '" data-filename="' + escaped_file_name + '" /> ' +
        '</li>\n');

    this.files_el.append(file_line);
};

// move uploaded file from ajax uploader into "finished" section
fuu.prototype._addFile = function (file_key, file_name) {
    this._addFileQuiet(file_key, file_name);
    this._showHideArchiveCheckbox();
    this._triggerChangeEvent();
};

fuu.prototype._removeFile = function (file_key) {
    jQuery('input[value=' + file_key + ']', this.files_el).parent().remove();
    if (jQuery('p', this.files_el).size() === 0)
        jQuery('.dd_keep_pre_uploaded', this.el).hide();

    this._showHideArchiveCheckbox();
    this._triggerChangeEvent();
};

fuu.prototype._triggerChangeEvent = function () {
    var event = jQuery.Event('dd_change');
    event.dd_object = this;
    jQuery('body').trigger(event);
};

fuu.prototype._triggerReadyEvent = function () {
    var event = jQuery.Event('dd_ready');
    event.dd_object = this;
    this.el.trigger(event);
};

fuu.prototype._isArchive = function (file_name) {
    var ext = file_name.substring(file_name.lastIndexOf(".") + 1).toLowerCase();
    return (ext === 'zip' || ext === 'rar');
};

fuu.prototype._openSelectModalWindow = function () {
    var w = jQuery('#browseUploaded');
    if (w.length == 0) {
        w = jQuery('#browseUploaded_');
        w.detach().attr('id', 'browseUploaded').prop('id', 'browseUploaded').appendTo('body');
    }
    w.modal();
	var mode = '';
	if (this.is_angular)
		mode = '&mode=angular';
    jQuery('.modal-body', w).load("/intranet/common/fuu_files_access.php?context=" + this.context + mode, null);

};

fuu.prototype._createFileUploader = function () {
    var _this = this;
    var fileUploaderSettings = {
        element: document.getElementById(this.context + 'ajax_uploader'),
        action: '/intranet/rest/documents/dropbox',
        debug: false,
        extraDropzones: jQuery('.qq-uploader-extra-dropzones'),

        listElement: jQuery('.dd_files_being_uploaded', _this.el).get(0),

        template: '<div class="qq-uploader">' +
        '<div class="qq-upload-drop-area"><span>' + lmsg('common.dropbox.drop_file_here') + '</span></div>' +
        '<div class="qq-upload-button btn btn-secondary">' + lmsg('common.dropbox.upload_a_file') + '</div>' +
        '</div>',

        // template for one item in file list
        fileTemplate: '<li>' +
        '<span class="qq-upload-spinner"></span>' +
        '<span class="qq-upload-file"></span>' +
        '<span class="qq-upload-size"></span>' +
        '<a class="qq-upload-cancel" href="#">' + lmsg('common.dropbox.cancel') + '</a>' +
        '<span class="qq-upload-failed-text">&bull; Failed</span>' +
        '</li>',

        classes: {
            // used to get elements from templates
            button: 'qq-upload-button',
            drop: 'qq-upload-drop-area',
            dropActive: 'qq-upload-drop-area-active',
            list: 'qq-upload-list',

            file: 'qq-upload-file',
            spinner: 'qq-upload-spinner',
            size: 'qq-upload-size',
            cancel: 'qq-upload-cancel',

            // added to list item when upload completes
            // used in css to hide progress spinner
            success: 'label-success',
            fail: 'label-important'
        },

        onComplete: function (id, fileName, responseJSON) {
            if (typeof responseJSON.file_key !== 'string') {
                if (cla != null) {
                    cla.showMessage(lmsg('common.upload_failed'), lmsg('common.please_contact_your_administrator'), true);
                }
                return;
            }

            _this.state = 'idle';
            _this._addFile(responseJSON.file_key, fileName);
            jQuery(_this.ajax_uploader._getItemByFileId(id)).remove();
        },
        //onSubmit: function(id, fileName){
        //_this.queue.push({'id' : id, 'file_name' : fileName});
        // console.log("Submit " + id + ' ' + fileName);
        //},
        onProgress: function (id, fileName, loaded, total) {
            _this.state = 'processing';
        },
        messages: {
            sizeError : lmsg("common.dropbox.max_size_error"),
            typeError: "{file} has invalid extension. Only {extensions} are allowed.",
            minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
            emptyError: "{file} is empty, please select files again without it.",
            onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
        },
        inputName: 'name',
        multiple: _this.allow_multiple_files
    };
    if (typeof _this.options.sizeLimit !== "undefined")
        fileUploaderSettings['sizeLimit'] = _this.options.sizeLimit;
    if (typeof _this.options.cancelOnInvalidFile !== "undefined")
        fileUploaderSettings['cancelOnInvalidFile'] = _this.options.cancelOnInvalidFile;

    this.ajax_uploader = new qq.FileUploader(fileUploaderSettings);

};

fuu.prototype._returnFileNameFromModalWindow = function (object, context) {
    //--- Parse incoming string ---

    var parts = object.id.split("->");
    var file_key = parts[0];
    var file_name = parts[1];

    this._addFile(file_key, file_name);
    jQuery('.dd_keep_pre_uploaded', this.el).show();
    jQuery('#browseUploaded').modal('hide');

    return false;
};


return fuu;
}));
