/// <reference path="../references.js" />

var rwthapp = rwthapp || {};

rwthapp.downloadL2PHelper = (function () {
    var me = {};
    me.f_name = "";
    me.mode = "";
    me.init = function (config) {
        return new Promise(function (resolve) {
            me.f_name = config.f_name;
            me.mode = config.mode;
            return rwthapp.connection.api.l2p[config.f](config.courseid).then(function (data) {
                var entries = rwthapp.fileRenderer.getFolderStructure(data);
                if (config.mode != "literature") me.renderModal(entries);
                else me.renderLiterature(entries);
                resolve(true);
            });
        });
    };

    me.renderModal = function (entries) {
        rwthapp.templateRenderer.render("#modal-content", "modal.downloadL2P.partial", entries);
        me.initButtons();
    };

    me.renderLiterature = function (entries) {
        rwthapp.templateRenderer.render("#literature-content", "l2p.courseDetails.literature.partial", entries);
        me.initButtons();
    };

    me.initButtons = function () {
        $(".file-download").click(function () {
            me.downloadFile($(this).data("filename"), $(this).data("fileid"), $(this).data("folder"));
        });
        $(".file-folderchange").click(function () {
            var items = rwthapp.fileRenderer.getFolderItems($(this).data("path"));
            if (me.mode != "literature") me.renderModal(items);
            else me.renderLiterature(items);
            me.initButtons();
        });
    };

    me.changeDirectory = function (path) {
        rwthapp.fileRenderer.actualDirectory = path;
        rwthapp.fileRenderer.render();
        me.initButtons();
    };

    me.downloadFile = function (name, fileId, folder) {
        folder = "RWTHAppDownload/" + rwthapp.templates.l2p.courseDetails.courseId + folder;
        var courseId = rwthapp.templates.l2p.courseDetails.courseId;
        rwthapp.connection.api.l2p.createDownloadLink(me.f_name + name + "?", { courseRoomId: courseId, fileid: fileId }).then(function (data) {
            rwthapp.fileManager.downloadFile(data, name, folder);
        })
    };

    return me;
})();