mod = angular.module('payrollhero.api')

class PagedArray
  hasMorePages: ->
    @page < @total_pages

mod.service 'PageInfoService', () ->
  this.addPageInfo = (data, array) ->
    if array
      if data && data.page
        array.page = data.page
        array.total_pages = data.total_pages
        array.per_page = data.per_page
        array.total_records = data.total_records || data.per_page * data.total_pages
      else
        array.page = 1
        array.total_pages = 1
        array.per_page = array.length
      _.extend(array, PagedArray.prototype)
  this

mod.factory 'PhRestangularV2', (PhRestangularBase, ApiBaseUri, PageInfoService) ->
  PhRestangularBase.withConfig (config) ->
    config.setBaseUrl(ApiBaseUri + '/v2')
  .addResponseInterceptor (data, operation, what, url, response, deferred) ->
    # return to Restangular {'employees'} as an array with paging methods.
    if operation is 'getList'
      PageInfoService.addPageInfo(data, data[what])
    else
      data

mod.factory 'PhRestangularV3', (PhRestangularV2, ApiBaseUri) ->
  PhRestangularV2.withConfig (config) ->
    config.setBaseUrl(ApiBaseUri + '/v3')

mod.factory 'PhRestangularV4', (PhRestangularBase, ApiBaseUri, PageInfoService) ->
  PhRestangularBase.withConfig (config) ->
    config.setBaseUrl(ApiBaseUri + '/v4')
  .addResponseInterceptor (data, operation, what, url, response, deferred) ->
    # return to Restangular {'employees'} as an array with paging methods.
    # V4 version uses the 'pagination' key for this stuff.
    if operation is 'getList'
      PageInfoService.addPageInfo(data.pagination, data[what])
    else
      data
