var express = require('express');
var app = express();
var url = require('url');
var request = require('request');

// Use envars on Heroku
if ( process.env.WU_API_KEY ) {
  var config = require('./config-sample.json');

  config.apikey = process.env.WU_API_KEY;
} else {
  var config = require('./config.json');
}

if ( process.env.PORT ) {
  config.port = process.env.PORT;
}

var format = ".json";

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

//use port is set in the environment variable, or 9001 if it isn’t set.
app.set( 'port', config.port );

//for testing that the app is running
app.get('/', function(req, res){
  var msg = 'Running!';

  if ( ! config.apikey.length ) {
    msg += ' Please set the API key.'
  }

  res.send( msg );
});

//app.post is triggered when a POST request is sent to the URL ‘/post’
app.post('/post', function(req, res){
  // Can't proceed without an API key
  if ( ! config.apikey.length ) {
    return res.sendStatus( 500 );
  }

  // Don't bother if there's nothing to look up
  if ( 'undefined' === typeof req.body.text || ! req.body.text.length ) {
    return res.sendStatus( 400 );
  }

  var parsed_url = url.format({
    pathname: 'http://api.wunderground.com/api/' + config.apikey + '/conditions/q/' + req.body.text + format,
  });

  console.log( req.body.text );

  request(parsed_url, function (error, response, body) {
    if ( error || 200 !== response.statusCode ) {
      return res.sendStatus( 500 );
    }

    // Get current conditions first
    var conditionData = JSON.parse( body );
    var temperature = conditionData.current_observation.temperature_string;
    var weatherCondition = conditionData.current_observation.weather;
    var icon_url = conditionData.current_observation.icon_url;
    var location = conditionData.current_observation.display_location.full;
    var obsLocation = conditionData.current_observation.observation_location.full;
    var stationID = conditionData.current_observation.station_id;

    parsed_url = url.format({
      pathname: 'http://api.wunderground.com/api/' + config.apikey + '/forecast/q/' + req.body.text + format,
    });

    request( parsed_url, function( error, response, body ) {
      // Basic response for the conditions data already obtained
      var responseBody = {
        "response_type": "in_channel",
        "text": '**' + location + "**\n" + obsLocation + ' (' + stationID + ')',
        "attachments": [
          {
            "text": "**Current conditions**\n"
                  + "Temperature: " + temperature + "\n"
                  + "Condition: " + weatherCondition,
            "image_url": icon_url
          }
        ]
      };

      // If forecast wasn't available, return just the conditions
      if ( error || 200 !== response.statusCode ) {
        responseBody.attachments[1] = { "text": "Could not retrieve forecast" };

        return res.send( responseBody );
      }

      // Build forecast into a table
      var forecastData = JSON.parse( body );

      var forecastBody = "---\n#### **Forecast as of " + forecastData.forecast.txt_forecast.date + "**\n";
      forecastBody += "| Day                 | Description                      | High   | Low    |\n";
      forecastBody += "|:--------------------|:---------------------------------|:-------|:-------|\n";
      forecastBody += "| Monday, Feb. 15     | Cloudy with a chance of flurries | 3 °C   | -12 °C |\n";
      forecastBody += '---';

      responseBody.attachments[1] = { "text": forecastBody };
      res.send( responseBody );

    });
  });
});

//tells Node which port to listen on
app.listen(app.get('port'), function() {
  console.log('Weather on the Slash is running on port', app.get('port'));
});