require('dotenv').config()
const Mastodon = require('mastodon-api');
const { OpenWeatherAPI } = require('openweather-api-node');

class BotClima {
  mastodon = null;
  weather = null;

  constructor(mastodon, weather) {
    this.mastodon = mastodon;
    this.weather = weather;
  }

  post(message) {
    this.mastodon.post('statuses', { status: message })
      .then(console.log)
      .catch(console.error);
  } 

  getCurrentWeather() {
    return this.weather.getCurrent();
  }
}

exports.handler = async (event, context) => {
  console.log(event);
  const mastodon = new Mastodon({
    api_url: 'https://mastodon.cl/api/v1/',
    access_token: process.env.MASTODON_ACCESS_TOKEN
  });
  
  const weather = new OpenWeatherAPI({
    key: process.env.OPENWEATHERAPI_KEY,
    language: 'es',
    locationName: process.env.OPENWEATHERAPI_CITY || 'Santiago, CL',
    units: 'metric'
  })

  const bot = new BotClima(mastodon, weather);
  const data = await bot.getCurrentWeather();
  console.log('Data', data );
  const message = `
  El reporte del clima en ${process.env.OPENWEATHERAPI_CITY} es:\n
  La temperatura actual es de ${data.weather.temp.cur}\u00B0C
  La humedad es del ${data.weather.humidity}%
  Vientos de ${data.weather.wind.speed} m/s
  Condición ${data.weather.description.charAt(0).toUpperCase() + data.weather.description.slice(1)}\n ${data.weather.icon.url}
  `;
  await bot.post(message);
  const response = { statusCode: 200, body: JSON.stringify(message) };
  return response;
};