(function() {
    'use strict';

    angular
        .module('eHaveApp')
        .service('dataService', dataService)
    
    dataService.$inject = ['$http', '$filter'];
    
    function dataService($http, $filter) {

        var dataService = {};
        
        var _getPatientData = function (optionsData) {
            return $http({
              method: 'GET',
              url: 'data/patients.json'
            })
            .then(function successCallback(response) {
                response = sortedData(response, optionsData);
                response = pagedData(response, optionsData);
                return response;
            },
                function errorCallback(response) {
                return response;
            });
        }

        var _getTestData = function (optionsData) {
            return $http({
              method: 'GET',
              url: 'data/tests.json'
            })
            .then(function successCallback(response) {
                return response;
            },
                function errorCallback(response) {
                return response;
            });
        }
        
        var sortedData = function (response,optionsData) {
            var records = response.data.Data;
            var sortField = optionsData.sort[0].field;
            var sortDir = optionsData.sort[0].dir;

            response.data.Data = $filter('orderBy')(records, sortField, sortDir=="asc")
            return response;
        }
        
        var pagedData = function (response,optionsData) {
            var records = response.data.Data;
            var firstRecord = optionsData.skip;
            var lastRecord = optionsData.take + optionsData.skip;

            response.data.Patients = records.slice(firstRecord, lastRecord);
            return response;
        }
        
        dataService.getPatientData = _getPatientData;
        dataService.getTestData = _getTestData;
        
        return dataService;
    }
})();        