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

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

rwthapp.templates.campus.details.rooms.gallery = {
    roomId:"",
    load: function (template, parameters) {
        var userId = rwthapp.tokenManager.getUserId();
        this.roomId = parameters.roomid;
        return rwthapp.connection.api.photo.getPhotosForRoom(parameters.roomid, userId).then(function (data) {
            var userId = rwthapp.tokenManager.getUserId();
            for (var i = 0; i < data.length; i++) {
                data[i].content = rwthapp.options.getProxyUrl() + data[i].content.replace("Thumb", "Photo");
                for (var j = 0; j < data[i].positiveRatings.length; j++) {
                    if (data[i].positiveRatings[j].userId == userId) {
                        data[i].isRated = "true";
                    }
                }
                for (var j = 0; j < data[i].warnings.length; j++) {
                    if (data[i].warnings[j].userId == userId) {
                        data[i].isWarned = "true";
                    }
                }
            }
            return {
                template: template,
                parameters: {
                    photos: data
                },
                title:rwthapp.localization.getLocalizedString("campus.details.rooms.gallery")
            };
        });
    },
    ready: function () {
        var me = this;
        $(".warn").on("click", function () {
            var userId = rwthapp.tokenManager.getUserId();
            var id = $(this).data("id");
            rwthapp.connection.api.photo.ratePhotoWarning(id, userId).then(function (data) {
                if (data.result == "warned") {
                    $("#warn" + id).css("color", "#e30066");
                } else {
                    $("#warn" + id).css("color", "#cfd1d2");
                }
            });
        });
        $(".rate").on("click", function () {
            var userId = rwthapp.tokenManager.getUserId();
            var id = $(this).data("id");
            rwthapp.connection.api.photo.ratePhotoPositive(id, userId).then(function (data) {
                if (data.result == "liked") {
                    $("#rate" + id).css("color", "#bdcd00");
                } else {
                    $("#rate" + id).css("color", "#cfd1d2");
                }
            });
        });
        $('#camera').on("click", function (e) {
            
            rwthapp.cameraHelper.showPhotoDialog().then(function (photoData) {
                if (photoData !== undefined) {
                    rwthapp.connection.api.photo.uploadPhotoForRoom(photoData.b64, me.roomId, rwthapp.tokenManager.getUserId(), photoData.angle).then(function (data) {
                        rwthapp.navigator.gotoPage("campus.details.rooms.gallery", { roomid: me.roomId }, false);
                    });
                }
            });
            // TODO add error handling
        });
    },

};