var express = require('express')
var router = express.Router()

const axios = require('axios')

/**
 * Services to add:
 * - https://unsplash.com/developers
 * - https://pixabay.com/api/docs/
 * 
 * Pronounciation will require $2/mo sub:
 * https://api.forvo.com/plans-and-pricing/
 */

async function pexelsSearch(query) {
    // https://help.pexels.com/hc/en-us/articles/47678194141337-Can-I-change-the-search-language-when-using-the-Pexels-API
    // pexels has a monthly rate limit and an hourly rate limit, only the monthly is returned in the headers
    // limit is also 200 per hour, will need to manually track that

    const resp = await axios.get(
      `https://api.pexels.com/v1/search?query=${encodeURIComponent(query)}&per_page=5`,
      {
        headers: {
          Authorization: process.env.PEXELS_API,
        },
      }
    )
  
    const { data, headers } = resp
    const photos = data.photos

    let filtered = photos.map((p) => (
      {
        url: p.src.medium,
        desc: p.alt,
        credit: p.photographer,
        id: p.id
      }
    ))

    let response = {
      photos: filtered,
      ratelimit: {
        limit: headers['x-ratelimit-limit'],
        remaining: headers['x-ratelimit-remaining'],
        reset: new Date(Number(headers['x-ratelimit-reset']) * 1000)
      }
    }

    return response;
}

async function shutterstockSearch(query) {

  // shutterstock has an hourly rate limit and no monthly limit
  // https://api-reference.shutterstock.com/?shell#assets-api
  // higher quality is available with shutterstock watermarks, look into [photo].assets objects

  const SHUTTERSTOCK_API_TOKEN = process.env.SHUTTERSTOCK_API

  try {
    const resp = await axios.get(
      'https://api.shutterstock.com/v2/images/search', 
      {
        headers: {
          'Accept': 'application/json',
          'Authorization': `Bearer ${SHUTTERSTOCK_API_TOKEN}`
        },
        params: {
          query,
          per_page: 5,
          sort: 'popular',
          safe: false,
          image_type: 'photo'
        }
      }
    )

    let { data, headers } = resp

    let filtered = data.data.map((p) => (
      {
        url: p.assets.mosaic.url,
        desc: p.description,
        credit: p.contributor.id,
        id: Number(p.id)
      }
    ))

    let response = {
      photos: filtered,
      ratelimit: {
        limit: headers['ratelimit-limit'],
        remaining: headers['ratelimit-remaining'],
        reset: new Date(Number(headers['ratelimit-reset']))
      }
    }

    return response;

  } catch (error) {
    console.error('Error:', error);
  }``
}

router.get('/', async function(req, res) {
  try {

    const queryL1 = req.query.queries[0]
    // const queryL2 = req.query.queries[1]

    // const pexels = await pexelsSearch(queryL1)
    const shutterstock = await shutterstockSearch(queryL1)

    response = shutterstock;

    res.status(200).send(response)
  } catch (err) {
    console.log(err)
  }
});

module.exports = router
