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

rwthapp.util.initNamespace("templates.campus.ub");

rwthapp.templates.campus.ub  = (function(){

    var ubData;
    var currentOpenedCollapsibles = [];
    var scrollContent;
    var clearCache = false;
    var lastOpenedCollapsibleState = [];
    var refreshActive = false;

    var load = function (template, parameters) {

        return rwthapp.connection.api.library.getAccount(clearCache).then(function (data) {

            ubData = data;

            if (ubData.BlockOrTrap.length > 0 && ubData.BlockOrTrap[0].blockAll) {

                ubData.locked = ubData.BlockOrTrap[0].localizedAccountLockedMessage;

                ubData.LoanedItem.forEach(function (element) {

                    element.actionPossible = false;
                });

                ubData.PrebookItem.forEach(function (element) {

                    element.blocked = true;
                });
            }
            else {

                ubData.PrebookItem.forEach(function (element, index) {

                    element.domId = "prebook" + index;
                });
            }

            ubData.LoanedItem.forEach(function (element) {

                var now = new Date();
                var dateDue = new Date(element.timestampDue);
                var daysBetweenDateDueAndNow = parseInt((dateDue.getTime() - now.getTime()) / (24 * 3600 * 1000));
  
                element.color = "rwth-green";
                element.textColor = "white-text";

                if (daysBetweenDateDueAndNow < 0) {

                    element.color = "rwth-red";
                }
                else if (daysBetweenDateDueAndNow <= 5) {

                    element.color = "rwth-yellow";
                    element.textColor = "black-text";
                }
            });

            ubData.totalDue = 0;

            ubData.AccountDetails.forEach(function (element) {

                element.monetaryValue = element.monetaryValue / 100;
                ubData.totalDue = ubData.totalDue + element.monetaryValue;
            });

            return {

                template: template,
                parameters: {

                    ub: ubData
                },
                title: rwthapp.localization.getLocalizedString("campus.ub.name"),
                tabletMode: { links: ['#das.channelDetails?channelId=fda4d69c-dd7b-4d4a-94a3-98cebecc9f59'], position: 'right', larger: true, large: 's7', small: 's5', noMainView: 'true' }
            };
        }).catch(function (error) {

            ubData = {

                error: rwthapp.langStrings.errors.api.general
            };

            ubData.isTablet = rwthapp.platformInfo.isTablet();

            if (error.apiStatusCode === 420) {

                ubData.error = error.apiStatusInfo;
            }
            else {
                
                rwthapp.error.handleError(error, location.hash);
            }

            return {

                template: template,
                parameters: {

                    ub: ubData
                },
                title: rwthapp.localization.getLocalizedString("campus.ub.name"),
                tabletMode: { links: ['#das.channelDetails?channelId=fda4d69c-dd7b-4d4a-94a3-98cebecc9f59'], position: 'right', larger: true, large: 's7', small: 's5', nomainview: 'true' }
            };
        });
    };

    var refreshUBPage = function () {

        refreshActive = true;

        clearCache = true;

        rwthapp.navigator.refreshPage().then(function () {

            clearCache = false;

            openAllOnceOpenedCollapsiblesInThisPageLifecycle();

            refreshActive = false;
        });

        return false;
    };

    var openAllOnceOpenedCollapsiblesInThisPageLifecycle = function () {

        // open current opened collapsibles again
        if (currentOpenedCollapsibles.length > 0) {

            $.each(currentOpenedCollapsibles, function (index, value) {

                $('#' + value).find('.collapsible-header').addClass("active");
                $('#' + value).find('.collapsible-body').attr("style", "display: block");
            });
        }
    };

    var ready = function () {

        openAllOnceOpenedCollapsiblesInThisPageLifecycle();

        scrollContent = $("html, body");

        rwthapp.util.addRightFeatureSpecificButtonToNavbar('ub-refresh', 'refresh', refreshUBPage);

        registerClickEvents();
    };

    var exit = function () {

        if (!refreshActive) {

            currentOpenedCollapsibles = [];
            lastOpenedCollapsibleState = [];
            rwthapp.util.removeRightFeatureSpecificButtonFromNavbar('ub-refresh');
        }
    };

    var registerClickEvents = function () {

        var clickCollapsible = function (type) {

            lastOpenedCollapsibleState = $.extend(true, [], currentOpenedCollapsibles);

            var addOrRemoveInCurrentOpenedCollapsibles = function (searchFor) {

                var result = -1;

                $.each(currentOpenedCollapsibles, function (index, value) {
                    
                    if (value === searchFor) {

                        result = index;
                        return false;
                    }
                });

                if (result === -1) {

                    currentOpenedCollapsibles.push(searchFor);
                }
                else {
                    
                    currentOpenedCollapsibles.splice(result, 1);
                }
            };

            var lengthbefore = currentOpenedCollapsibles.length;

            switch (type) {

                case 'LOAN':
                    addOrRemoveInCurrentOpenedCollapsibles('loaningCollapsible');
                    break;
                case 'ORDER':
                    addOrRemoveInCurrentOpenedCollapsibles('orderingCollapsible');
                    break;
                case 'PREBOOK':
                    addOrRemoveInCurrentOpenedCollapsibles('prebookCollapsible');
                    break;
                case 'PAYMENT':
                    addOrRemoveInCurrentOpenedCollapsibles('paymentCollapsible');
                    break;
            }

            if (scrollContent && currentOpenedCollapsibles.length > lengthbefore && $('#ubContent').height() >= $(window).height() - $('#navigationBar').height()) {

                var y = $(window).scrollTop();

                if (rwthapp.platformInfo.isTablet()) {

                    y = scrollContent.scrollTop();
                }

                scrollContent.animate({ scrollTop: y + 100 }, 400, "swing");
            }
        };

        $('#loaningCollapsible').click(function () { clickCollapsible('LOAN'); } );
        $('#orderingCollapsible').click(function () { clickCollapsible('ORDER'); } );
        $('#prebookCollapsible').click(function () { clickCollapsible('PREBOOK'); });
        $('#paymentCollapsible').click(function () { clickCollapsible('PAYMENT'); });

        $('#libraryData .rwthapp_ub_action').click(function () {

            if($(this).hasClass("disabled")) {

                return;
            }

            if ($(this).data("feature") === 'renewItem') {

                rwthapp.util.showLoadingScreen();
                $('#ubError').empty();

                rwthapp.connection.api.library.renewItem($(this).data("parameter")).then(function (data) {

                    currentOpenedCollapsibles = lastOpenedCollapsibleState;

                    rwthapp.navigator.currentPage.target.parameters.clearCache = "true";

                    // show the renewed item in right sequence which new color
                    refreshUBPage();

                }).catch(function(error) { 
                    
                    currentOpenedCollapsibles = lastOpenedCollapsibleState;

                    rwthapp.util.hideLoadingScreen();

                    if (error.apiStatusCode === 420) {

                        $('#ubError').text(error.apiStatusInfo);
                        rwthapp.notifications.showToast(error.apiStatusInfo, 5000);
                    }
                    else {

                        rwthapp.error.handleError(error);
                    }
                });
            }

            if ($(this).data("feature") === 'cancelRequestedItem') {

                currentOpenedCollapsibles = lastOpenedCollapsibleState;

                rwthapp.util.showLoadingScreen();
                $('#ubError').empty();

                var domId = $(this).data("domid");
                var parameter = $(this).data("parameter");

                rwthapp.connection.api.library.cancelRequestedItem(parameter).then(function (data) {

                    $('#' + domId).remove();
                    $('#prebook_badge').text(parseInt($('#prebook_badge').text()) - 1);

                    rwthapp.util.hideLoadingScreen();

                }).catch(function(error) {
                  
                    currentOpenedCollapsibles = lastOpenedCollapsibleState;

                    rwthapp.util.hideLoadingScreen();

                    if (error.apiStatusCode === 420) {

                        $('#ubError').text(error.apiStatusInfo);
                        rwthapp.notifications.showToast(error.apiStatusInfo, 5000);
                    }
                    else {

                        rwthapp.error.handleError(error);
                    }
                });
            }
        });
    };

    return {

        load: load,
        ready: ready,
        exit: exit
    };
})();