(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) {

//                console.log("_getPatientData:options");
//                console.log(optionsData);
                response = sortedData(response, optionsData);
                response = pagedData(response, optionsData);
//                console.log("_getPatientData:response");
//                console.log(response);
                
                
                return response;
            },
                function errorCallback(response) {
                return response;
            });
        }

        var _getTestData = function (optionsData) {
            return $http({
              method: 'GET',
              url: 'data/tests.json'
            })
            .then(function successCallback(response) {
                return $filter('filter')(response.data.Data, { 
                    MRN: optionsData.MRN 
                });
            },
                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.Data = records.slice(firstRecord, lastRecord);
            
            return response;
        }
        
        dataService.getPatientData = _getPatientData;
        dataService.getTestData = _getTestData;
        
        return dataService;
    }
})();        