'use strict';

/** 
 * @controller PollMainController
 * @property scope 
 * @property route
 * @property location
 * @property window
 * @property System
 * @property PollService
 * @property Resource
 */

var App = angular.module('polls.controllers.main', [
    'system'
])
    .controller('PollMainController', [
        '$scope',
        '$location',
        '$window',
        '$route',
        'System',
        'PollService',     
        function ($scope, $location, $window, $route, System, PollService) {
            System.Page.title("Polls");
            $scope.query = $route.current.params || {};
            $scope.Status = $route.current.params["Status"] || "";
            $scope.sorter = System.Sorter.create($scope.query);
            $scope.poll = {};
            $scope.newPoll = {};
            $scope.sidebarView = 'basic';
            $scope.aktivan = true;
            $(".tooltip").tooltip();

            $scope.statuses = [
                { id: 0, title: 'Draft' },
                { id: 1, title: 'Pending' },
                { id: 2, title: 'Live' },
                { id: 3, title: 'Archived' },
                { id: 4, title: 'Deleted' },
                { id: 5, title: 'Aktivan' },
                { id: 6, title: 'NeAktivan' }

            ];

            /**
            * @method refresh
            * @description refreshes page and loads all initial data
            */
            $scope.refresh = function () {
                PollService.query($scope.query).then(function (data) {
                    $scope.polls = data.polls;
                    $scope.pager = System.Pager.create({ page: $scope.query.page, total: data.total });
                    for (var i = 0; i < data.polls.length; i++) {
                        var s = data.polls[i].Status.Value;
                        if (s == 5)
                            $scope.aktivan = false;
                    }


                });
            };


            /**
              * @method isSearch
               * @description returns value indicates if search is running
             */
            $scope.isSearch = function () {
                return Object.keys($scope.query).length !== 0;
            };


            /**
            * @method reset
            * @description resets search to its initial value
            */
            $scope.resets = function () {
                $location.search(($scope.query = {}));
                $scope.refresh();
            };
            /**
           * @method search
           * @description searches radnici 
           */
            $scope.search = function (q, reset) {
                reset ? $scope.query = q : angular.extend($scope.query, q);
                $location.search($scope.query);
                $scope.refresh();
            };




            qusion.queryToArray = function (input, separator) {
                if (!separator) separator = ',';
                if (input && input.indexOf(separator) > -1)
                    input = input.split(separator);
                if (!input)
                    input = [];
                return input;
            };

            /**
            * @method search
            * @description searches polls 
            */
            $scope.search = function (q, reset) {
                reset ? $scope.query = q : angular.extend($scope.query, q);
                $location.search($scope.query);
                $scope.refresh();
            };

            $scope.switchSidebar = function (view) {
                $scope.sidebarView = view;
            };

            /**
            * @method sort
            * @description sorts polls
            */
            $scope.sort = function (by, dir) {
                $scope.sorter.sort(by, dir);
                $location.search($scope.query);
                $scope.refresh();
            };

            /**
            * @action select selects single poll and redirects user to poll details
            * @param poll poll instance to view details for
            */
            $scope.select = function (agent) {
                $location.url('/polls/' + agent.ID);
            };

            /**
            * @method create
            * @description Creates new poll
            */
            $scope.create = function () {
                PollService.create($scope.newPoll).then(function (response) {
                    if (response.Errors) {
                        $scope.errors = response.Errors;
                        System.Message.error($scope.$resource('polls.PollCreatedError'));
                    } else {
                        $scope.refresh();
                        System.Message.success($scope.$resource('polls.PollCreated'));
                    }
                });
            };

            $scope.updatePoll = function (poll) {
                $scope.poll = poll;
                $scope.dialogUpdatePoll.dialog("open");
            };

            $scope.dialogUpdatePoll = {};

            $scope.ui.dialogUpdatePoll = {
                width: 700,
                title: $scope.$resource('polls.edit'),
                create: function () {
                    $scope.dialogUpdatePoll = $(this);
                }
            };

            /**
            *@method cancelUpdate Close dialog and clears dialog data.
            */
            $scope.cancelUpdate = function () {
                $scope.refresh();
                $scope.dialogUpdatePoll.dialog("close");
            };

            /**
            * @method edit
            * @description Updates poll after successfull edit
            */
            $scope.edit = function () {
                PollService.edit($scope.poll).then(function (poll) {
                    if (poll.Errors) {
                        $scope.errors = poll.Errors;
                        System.Message.error($scope.$resource('polls.PollCreatedError'));
                    } else {
                        $scope.poll = poll;
                        $scope.refresh();
                        $scope.dialogUpdatePoll.dialog("close");
                        System.Message.success($scope.$resource('polls.PollUpdated'));
                    }

                });
            };

            /**
            * @method remove
            * @param id
            * @description Removes poll by its id
            */
            $scope.remove = function (poll, index) {
                if ($window.confirm($scope.$resource('utility.areYouShure'))) {
                    PollService.remove({ id: poll.ID }).then(function (response) {
                        if (response.Error) {
                            $scope.errors = response.Errors;
                            System.Message.error($scope.$resource('utility.changeNotSave'));
                        } else {
                            $scope.polls.splice(index, 1);
                            $scope.refresh();
                            System.Message.success($scope.$resource('utility.deleted'));
                        }
                    });
                }
            };

            $scope.setLock = function (poll) {
                PollService.setLockStatus(poll.ID).then(function (data) {
                    poll.Status = data.Status;
                    if (data.Status.Name == "Aktivan") {
                        System.Message.success($scope.$resource("polls.unlocked"));
                        $scope.aktivan = false;
                        $scope.refresh();
                    } else {
                        System.Message.success($scope.$resource("polls.locked"));
                        $scope.aktivan = true;
                        $scope.refresh();
                    }
                });
            };
            /**
           * @action newPost returns to location /post/id/create
           */
            $scope.newQuestion = function (agent) {
                $location.url('/question/' + agent.ID + '/create');
            };

            $scope.$watch("pager.page", function () {
                if (!$scope.pager || !$scope.pager.page) return;
                $scope.query.page = $scope.pager.page;
                $scope.search($scope.query, false);
            });

            $scope.refresh();
        }
    ]);

        App.filter('pollFilter', [function () {
            return function (polls, Status) {
                if (Status !="" && Status != null) {
                    var tempPolls = [];
                    for (var i = 0; i < polls.length; i++) {
                        if (polls[i].Status.DisplayName == Status) {
                            tempPolls.push(polls[i]);
                        }
                    };
                    return tempPolls;
                } else {
                    return polls;
                }
            };
        }]);