const axios = require('axios')
const { RateLimiter } = require('limiter')

class Api {
  constructor () {
    this.baseUrl = 'https://api.warframe.market/v1/'
    this.delay = process.env.API_DELAY ?? 3000
    this.limiter = new RateLimiter({ tokensPerInterval: 1, interval: Number(this.delay) })
  }

  async _get (url) {
    await this.limiter.removeTokens(1)
    return axios.get(url).catch((error) => {
      console.error(error)
      return {
        data: {
          payload: {
            orders: []
          }
        }
      }
    })
  }

  async getOrders (url) {
    const response = await this._get(this.baseUrl + 'items/' + url + '/orders')
    return response.data.payload.orders.filter(function (order) {
      return order.order_type === 'sell' && order.user.status !== 'offline'
    })
  }

  async getSortedOrders (url) {
    const orders = await this.getOrders(url)
    return orders.sort(function (a, b) {
      return a.platinum - b.platinum
    })
  }
}

module.exports = new Api()
