'use strict';

var PageService = angular.module('pages.services', [
    'system'
])
    .factory('PageService', [
        '$http',
        '$q',
        'System',
        'PageFactory',
        function($http, $q, System, PageFactory) {

            var URL = {
                QUERY: '/cms/api/pagelaktasi/query',
                GET: '/cms/api/pagelaktasi/get',
                ROOT: '/laktasiapi/pagelaktasi/root',
                TOP: '/cms/api/pagelaktasi/top',
                REORDER: '/cms/api/pagelaktasi/Reorder'
            };

            var query = function(params) {
                var deferred = $q.defer();
                $http.get(URL.QUERY, {
                    params: params
                })
                    .success(function(data) {
                        var pages = [];
                        for (var i = 0; i < data.Items.length; i++) {
                            pages.push(PageFactory.create(data.Items[i]));
                        }
                        deferred.resolve({ pages: pages, total: data.Count });
                    });

                return deferred.promise;
            };

            var top = function(tip) {
                var deferred = $q.defer();
                $http.get(URL.TOP, {
                    params: {tip:tip}
                })
                    .success(function(data) {
                        var pages = [];
                        for (var i = 0; i < data.Items.length; i++) {
                            pages.push(PageFactory.create(data.Items[i]));
                        }
                        deferred.resolve({ pages: pages, total: data.Count });
                    });

                return deferred.promise;
            };

            var get = function(id) {
                var deferred = $q.defer();
                $http.get(URL.GET, {
                    params: { id: id }
                }).success(function(data) {
                    var page = PageFactory.create(data);
                    deferred.resolve(page);
                });

                return deferred.promise;
            };

          
            var reorder = function (data) {
                var deferred = $q.defer();
                $http.post(URL.REORDER, { Pages: data }).success(function (page) {
                    deferred.resolve(page);
                });

                return deferred.promise;
            };

            var root = function(id) {
                var deferred = $q.defer();
                $http.post(URL.ROOT + '/' + id)
                    .success(function(data) {
                        var page = PageFactory.create(data);
                        deferred.resolve(page);
                    });

                return deferred.promise;
            };

            return {
                query: query,
                get: get,
                root: root,
                top: top,
                reorder: reorder
            };
        }
    ]);