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

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

rwthapp.templates.campus.details.courses = (function () {
    var courseId;

    var loadAppointments = function (gguid) {
        return rwthapp.connection.api.campus.getAppointments(gguid).catch(function (error) {
            // Still display page but without appointments
            rwthapp.logging.logger.error("Appointments could not be retrieved.", error);
            return [];
        });
    };

    var loadPersonalizedAppointments = function (gguid) {
        return rwthapp.connection.api.campus.getPersonalizedAppointments(gguid).catch(function (error) {
            if (error.apiStatusCode === -1) {
                // Fallback if personalized appointments cannot be retrieved (fails for some courses)
                // TODO add custom error code on proxy side
                return rwthapp.connection.api.campus.getAppointments(gguid);
            } else {
                throw error;
            }
        }).catch(function (error) {
            // Still display page but without appointments
            rwthapp.logging.logger.error("Personalized appointments could not be retrieved.", error);
            return [];
        });
    };

    var load = function (template, parameters) {
        courseId = parameters.gguid;
        var appointmentFunction = rwthapp.tokenManager.isLoginPersonalized() ? loadPersonalizedAppointments : loadAppointments;
        return Promise.all([rwthapp.connection.api.campus.getCourseById(parameters.gguid), appointmentFunction(parameters.gguid)]).then(function (data) {
            data[0].appointments = data[1];
            data[0].loggedIn = rwthapp.tokenManager.isLoginPersonalized();

            if (parameters.startTimestamp && parameters.endTimestamp) {

                while(data[0].appointments.length > 1) {

                    var value = data[0].appointments[0];

                    if (JSON.stringify(value.timestampstart) !== parameters.startTimestamp && JSON.stringify(value.timestampend) !== parameters.endTimestamp) {

                        data[0].appointments.splice(0, 1);
                    }
                    else {

                        data[0].appointments = [data[0].appointments[0]];
                    }
                }
            }

            return {
                template: template,
                parameters: {
                    course: data[0]
                },
                title: rwthapp.localization.getLocalizedString("titles.event"),
                subTitle: data[0].title + " (" + data[0].term + ")",
                tabletMode: { links: ['#campus.search?type=courses', '#organisation.timetable'], position: 'left' }
            };
        });
    };

    var ready = function () {
        // TODO do not show checkboxes if logged in anonymously
        if (rwthapp.tokenManager.isLoginPersonalized()) {
            $(".addAppointment").click(function () {
                var gguid = $(this).data("gguid");
                var me = this;
                if ($(this).prop("checked")) {
                    rwthapp.connection.api.campus.addEvent(courseId, gguid).then(function (data) {
                        rwthapp.notifications.showToastShort(rwthapp.localization.getLocalizedString("campus.details.courses.addEvent"));
                    }).catch(function (e) {
                        rwthapp.notifications.showToastShort(rwthapp.localization.getLocalizedString("campus.details.courses.addEventFailed"));
                        $(me).prop("checked", false);
                    });
                } else {
                    rwthapp.connection.api.campus.deleteEvent(courseId, gguid).then(function (data) {
                        rwthapp.notifications.showToastShort(rwthapp.localization.getLocalizedString("campus.details.courses.deleteEvent"));
                    }).catch(function (e){
                        rwthapp.notifications.showToastShort(rwthapp.localization.getLocalizedString("campus.details.courses.deleteEventFailed"));
                        $(me).prop("checked", false);
                    });
                }
            });
        }
    };

    return {
        load: load,
        ready: ready
    };
})();