'use strict'

const tickerRouter = require('express').Router()
const axios = require('axios')
const { redisClient } = require('../../server')
const { thirdPartyApis, REDIS_EXPIRE } = require('../settings')

function decodeTickerResponse(apiSource, data) {
  switch (apiSource) {
    case 'bitstamp':
      return data.last // TODO mv to settings?
      break
    case 'coinbase':
      return data.data.amount
      break
    case 'coinmarketcap':
      return data[0].price_usd
      break
    case 'shapeshift':
      return data.rate
      break
    default:
      return result
  }
}

function getFromThirdPary(apiSource, symbol, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' })
  const redisKey = apiSource + symbol
  console.log('key', redisKey);
  redisClient.get(redisKey, (err, data) => {
    if (err) throw err
    if (data != null) {
      console.log('stored in redis');
      res.end(JSON.stringify({ price: data }))
    } else {
      console.log('get from 3rd party')
      const apiUrl = thirdPartyApis[apiSource].ticker + symbol + (apiSource === 'coinbase' ? '/spot' : '')
      axios.get(apiUrl)
        .then((result) => {
          const price = decodeTickerResponse(apiSource, result.data)
          redisClient.setex(redisKey, REDIS_EXPIRE, price)
          res.end(JSON.stringify({ price, timestamp: new Date() }))
        })
        .catch((err) => {
          console.error(err)
        })
    }
  })
}

tickerRouter.get('/:exchange/:symbol', (req, res) => {
  const { exchange, symbol } = req.params
  getFromThirdPary(exchange, symbol, res)
})

module.exports = tickerRouter

@@ -638,63 +638,8 @@
 ) %7B%0A
-  res.writeHead(200, %7B 'Content-Type': 'text/plain' %7D)%0A
   co
@@ -954,16 +954,45 @@
 apiUrl =
+ thirdPartyApis%5BapiSource%5D &&
  thirdPa
@@ -1070,16 +1070,128 @@
 ' : '')%0A
+      if (!apiUrl) %7B%0A        res.status(400).send(%7B error: 'Bad Request. Invalid Exchange.' %7D)%0A      %7D else %7B%0A  
       ax
@@ -1248,21 +1248,14 @@
     
-const price =
+return
  dec
@@ -1308,57 +1308,215 @@
     
-  redisClient.setex(redisKey, REDIS_EXPIRE, price
+%7D)%0A        .then((price) =%3E %7B%0A          if (!price) %7B throw new Error('Bad Symbol.') %7D%0A          redisClient.setex(redisKey, REDIS_EXPIRE, price)%0A          res.writeHead(200, %7B 'Content-Type': 'text/plain' %7D
 )%0A  
@@ -1651,26 +1651,89 @@
 rr)%0A        
+  res.status(400).send(%7B error: err.message %7D)%0A        %7D)%0A      
 %7D
-)
 %0A    %7D%0A  %7D)%0A

handle bad req