'use strict';
/*
 * Service to controll notifications
 *
 error object looks like:

    obj[error_type]['errorCode'] = could be 404, 500 ..
    obj[error_type]['text']      = any text

 *
 */

angular.module('notificationServiceModule', [])
    .factory('notificationService', function($rootScope, $timeout) {
    var self = this;

    self.$timeout = $timeout;

    var $scope = {};
    $scope.notification = {};

    $rootScope.$on('modalClose', function() {
        self.notification.resetNotification();
    });

    self.notification = {
        getNotifications: function()
        {
            return $scope.notification;
        },
        /*This function will create error object. Use it for manual errors and warnings, errors from PHP already in the right format */
        createObjectForNotification: function(type, errorCode, text) {
            var error  = {};

            error.type = $.trim(type) !== '' ? type : 'error';
            error.data = [];
            error.data[0] = {};
            error.data[0].text      = $.trim(text) !== '' ? text      : 'Query returned 0 rows';
            error.data[0].errorCode = errorCode    !== '' ? errorCode : '555';
            return error;
        },
        setNotification: function(type, data, callbackFnc, callbackParams) {
            $scope.notification = {};
            $scope.notification[type] = {};
            //some workaround if error just a plain text, to make this compatible with all MP calls, like session expire
            if (angular.isArray(data))
            {
                $scope.notification[type].text      = data[0].text;
                $scope.notification[type].errorCode = data[0].errorCode;
            }
            else
            {
                $scope.notification[type].text      = data;
                $scope.notification[type].errorCode = 500;
            }
            $timeout(function(){
                $rootScope.$broadcast('setNotification');
            }, self.notification.notificationDelay);
        },
        resetNotification: function() {
            $scope.notification  = {};
            $rootScope.$broadcast('resetNotificationMessage');
        }
    };
    return  self.notification;
});