'use strict';

angular.module('blogs.services', [
    'system'
])
    .factory('BlogService', [
        '$http',
        '$q',
        'System',
        'BlogFactory',
        function ($http, $q, System, BlogFactory) {

            var URL = {
                QUERY: '/cms/api/bloglaktasi/query',
                QUERY_POSTS: '/cms/api/bloglaktasi/queryPosts',
                GET: '/cms/api/bloglaktasi/get',
                GET_POST_FOR_EDIT: '/cms/api/bloglaktasi/postForEdit',
           
            };
            
            var query = function (params) {
                var deferred = $q.defer();
                $http.get(URL.QUERY, {
                    params: params
                })
                    .success(function(data) {
                        var blogs = [];
                        for (var i = 0; i < data.Items.length; i++) {
                            blogs.push(BlogFactory.create(data.Items[i]));
                        }
                        deferred.resolve({ blogs: blogs, total: data.Count });
                    });

                return deferred.promise;
            };
            
            var queryPosts = function (params) {
                var deferred = $q.defer();
                $http.get(URL.QUERY_POSTS, {
                    params: params
                })
                    .success(function (data) {
                        var posts = [];
                        for (var i = 0; i < data.Items.length; i++) {
                            posts.push(BlogFactory.create(data.Items[i]));
                        }
                        deferred.resolve({ posts: posts, 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 blog = BlogFactory.create(data);
                    deferred.resolve(blog);
                });
                
                return deferred.promise;
            };
            
            var getForEdit = function (id) {
                var deferred = $q.defer();
                $http.get(URL.GET_POST_FOR_EDIT, {
                    params: { id: id }
                }).success(function (data) {
                   var post = data;
                    deferred.resolve(post);
                });
                return deferred.promise;
            };

        

            return {
                query: query,
                get: get,
                getForEdit: getForEdit,
                queryPosts: queryPosts
            };
        }
    ]);
