const Client = require('request-json');
const logger = require('log4js').getLogger('Weather');
const weather = require('openweather-apis');
const { reduceWeather } = require('./reducers/weather');

logger.level = 'debug';

const openWeatherApiKey = process.env.openweatherAPI || '936a0ed9eb23b95cf08fc9f693c24264';

const darkskyApiKey = process.env.darkskyApiKey || '9ad2a41d420f3cf4960571bb886f710c';
const DSclient = Client.createClient(`https://api.darksky.net/forecast/${ darkskyApiKey }/`);

weather.setAPPID(openWeatherApiKey);
weather.setLang('en');
// weather.setCity('Glasgow City');

function doGetOpenWeather(ll) {
  const [lat, long ] = ll.split(',');

  return new Promise((resolve, reject) => {
    weather.setCoordinate(lat, long);
    weather.getWeatherForecast( function(err, wData) {
      if (err)
        return reject(err);
      else
        return resolve(wData);
    });
  });
}

function doGetOpenWeatherForecast(ll) {
  const [lat, long ] = ll.split(',');

  return new Promise((resolve, reject) => {
    weather.setCoordinate(lat, long);
    weather.getWeatherForecastForDays(5, function(err, wData) {
      if (err)
        return reject(err);
      else
        return resolve(wData);
    });
  });
}

function doGetDarkSkyWeather(ll) {
  const query = `${ll}?units=uk2&exclude=daily,flags,minutely,hourly`;

  return new Promise((resolve, reject) => {
    DSclient.get(query, function(err, res, body) {
      if (err || !body || !body.currently)
        return reject(err);

      return resolve(body);
    });
  });
}

function doGetFullForcast(ll) {
  const query = `${ll}?units=uk2&exclude=flags,minutely`;

  return new Promise((resolve, reject) => {
    DSclient.get(query, function(err, res, body) {
      if (err || !body || !body.currently)
        return reject(err);

      const output = reduceWeather(body);

      return resolve(output);
    });
  });
}

module.exports = { doGetOpenWeather, doGetOpenWeatherForecast, doGetDarkSkyWeather, doGetFullForcast };
