'use strict';

var ArticleService = angular.module('articles.services', [
    'system'
])
    .factory('ArticleService', [
        '$http',
        '$q',
        'System',
        'ArticleFactory',
        function($http, $q, System, ArticleFactory) {

            var URL = {
                ALL: '/cms/api/articlelaktasi/query',
                FOUR: '/cms/api/articlelaktasi/queryfour',
                GET: '/cms/api/articlelaktasi/get'
            };

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

                return deferred.promise;
            };

            var queryfour = function (params) {
                var deferred = $q.defer();
                $http.get(URL.FOUR, {
                    params: params
                })
                    .success(function (data) {
                        var articles = [];
                        for (var i = 0; i < data.Items.length; i++) {
                            articles.push(ArticleFactory.create(data.Items[i]));
                        }
                        deferred.resolve({ articles: articles, 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 article = ArticleFactory.create(data);
                    deferred.resolve(article);
                });

                return deferred.promise;
            };
 
            return {
                query: query,
                queryfour: queryfour,
                get: get
            };
        }
    ]);