import http from 'http';
import * as url from "url";
import fetch from 'node-fetch';

function json_response(code, object, response) {
  response.statusCode = 200;
  response.setHeader('content-type', 'Application/json');
  response.end(JSON.stringify(object));
}

const server = http.createServer(function (request, response) {
  let parsedUrl = url.parse(request.url, true);
  if(request.method === "POST") {
    console.log('POST');
    if(parsedUrl.query.param)
    {
      json_response(200,parsedUrl.query,response);
    }
    else
    {
      json_response(400,{error:"missing required param"},response);     
    }
  }
  else if(request.method === "PUT") {
    console.log('PUT');
    json_response(200,{status : "where should I put it ?"},response);
  }
  else if(request.method === "DELETE") {
    console.log('DELETE');
    json_response(200,{status : "no delete available"},response);
  }  
  else
  {
    console.log(request.method);
    console.log(parsedUrl.query.address);
    getLatLong(parsedUrl.query.address, response);
    json_response(200,{status : "active"},response);
  }
});
server.listen(8081);

function getLatLong(address, response) {

    let result = null;
    /* Create a new promise and send geocoding request */
    var promise = new Promise((resolve, reject) => {
        var apiKey = "b814900746f646f0a21765274c98f387";
        var url = `https://api.geoapify.com/v1/geocode/search?text=${encodeURIComponent(address)}&apiKey=${apiKey}`;
        console.log(url);
        fetch(url).then(response => {
            if (response.ok) {
                response.json().then(data => resolve(data));
            } else {
                response.json().then(data => reject(data));
            }               
        });
    }); 

    promise.then((data) => {
        console.log(data.features[0].properties);
        getWeatherAtLatLong(data.features[0].properties.lat, data.features[0].properties.lon, response);
    }, (err) => {
        if (!err.canceled) {
            console.log(err);
          }        
    });
}

function getWeatherAtLatLong(lat,long, response) {
    console.log('getWeatherAtLatLong('+lat+','+long+')');
}