'use strict';

var MessageCtrl = ['$scope', '$location', 'dateFilter', 'message', 'tags', 'users', 'priorities', function ($scope, $location, dateFilter, message, tags, users, priorities) {
    $scope.message = message;
    $scope.priorities = priorities
    $scope.tags = tags;
    $scope.users = users;

    message.Posts.push({Readonly: false});

    $scope.addTag = function (tag) {
        tags.push(tag);
        message.Tags.push(tag);
    };

    $scope.edit = function (post) {
        post.Readonly = false;
    };

    $scope.save = function () {
        if (!$scope.message.Title.length) {
            $scope.toasts.push({Type: 'Danger', Message: 'Message Title Blank'});
            return;
        }
        for (var i = 0, l = $scope.message.Posts.length; i < l; i++) {
            if (angular.isDate($scope.message.Posts[i].Date)) {
                $scope.message.Posts[i].Date = dateFilter($scope.message.Posts[i].Date, 'dd-MMM-yyyy');
            }
        }

        $scope.message.$save(function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: ''});
            $location.path('/');
        }, function (data, status) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };
    $('#txtTitle').focus();
}];

MessageCtrl.resolve = {
    message: ['$route', 'Message', function ($route, Message) {
        var id = $route.current.params.id;

        return Message.get({id: id}).$promise;
    }],
    tags: ['$q', 'Tag', function ($q, Tag) {
        var deferred = $q.defer();
        var successCb = function (result) {
            var len = result.length;
            var i = 0;
            var list = [];
            for (i = 0; i < len; i++) {
                list.push(result[i].Name);
            }
            deferred.resolve(list);
        };
        Tag.query({}, successCb);
        return deferred.promise;
    }],
    users: ['$q', 'User', function ($q, User) {
        var deferred = $q.defer();
        var successCb = function (result) {
            var len = result.length;
            var i = 0;
            var list = [];
            for (i = 0; i < len; i++) {
                list.push(result[i].Name);
            }
            deferred.resolve(list);
        };
        User.names({}, successCb);
        return deferred.promise;
    }],
    priorities: [function () {
        return [
            {id: 1, name: 'Critical'},
            {id: 2, name: 'Urgent'},
            {id: 3, name: 'Semi-Urgent'},
            {id: 4, name: 'Normal'},
            {id: 5, name: 'Below-Normal'},
            {id: 6, name: 'Casual'}
        ];
    }]

};
