'use strict';

var KartaService = angular.module('karta.services', [
    'system'
])
    .factory('KartaService',  [
        '$http',
        '$q',
        'System',
        'KartaFactory',
        function ($http, $q, System, KartaFactory) {

            var URL = {
                QUERY: '/qusion/api/Karta/query',
                GET: '/qusion/api/Karta/get',
                CREATE: '/qusion/api/Karta/create',
                EDIT: '/qusion/api/Karta/edit',
                DELETE: '/qusion/api/Karta/delete'
            };




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

                return deferred.promise;
            };


            var create = function (karta) {
                var deferred = $q.defer();
                $http.post(URL.CREATE, karta)
                    .success(function (data) {
                        karta = KartaFactory.create(data);
                        deferred.resolve(data);
                    });
                return deferred.promise;
            };

            var edit = function (karta) {
                var deferred = $q.defer();
                $http.post(URL.EDIT, Karta)
                    .success(function (data) {

                        deferred.resolve(data);
                    });

                return deferred.promise;
            };

            var remove = function (params) {
                var deferred = $q.defer();
                $http.get(URL.DELETE, {
                    params: params
                })
                    .success(function (data) {

                        deferred.resolve(data);
                    });

                return deferred.promise;
            };
        
            return {
                query: query,
                get: get,
                create: create,
                edit: edit,
                remove: remove
            };
        }
    ]);
