var _ = require('underscore');
var express = require('express');

var db = require('../helpers/db');
var isBadRequest = require('../helpers/request-checker');

var router = express.Router();

var createTagQuery = function(id, tags) {
  var query = 'INSERT INTO tags ("place_id", "characteristic_id") VALUES ';

  for (var tag in tags) {
    query += ('(' + id + ', ' + tags[tag] + ')');

    if (tags[tag] === _.last(tags)) {
      query += ';';
    } else {
      query += ', ';
    }
  }

  return query;
};

var updateTags = function(id, tags) {
  var tagQuery = 'DELETE FROM tags WHERE tags.place_id = $1';
  var tagValues = [id];

  db.query(tagQuery, tagValues)
    .then(function(result) {
      tagQuery = createTagQuery(id, tags);

      db.query(tagQuery)
        .then(function(result) {
          return true;
        })
        .catch(function(error) {
          return error;
        });
    })
    .catch(function(error) {
      return error;
    });
};

router.get('/', function(req, res) {
  var query = "SELECT place_id, places.name, countries.name AS country, description, places.image, latitude, longitude, link, enabled FROM places LEFT JOIN countries ON countries.country_id = places.country_id ORDER BY place_id ASC";

  db.query(query)
    .then(function(result) {
      res.status(200).send(result.rows);
    })
    .catch(function(error) {
      res.status(500).send(error);
    });
});

router.post('/', function(req, res) {
  var values = [
    req.body.country_id,
    req.body.name,
    req.body.description,
    req.body.image,
    req.body.latitude,
    req.body.longitude,
    req.body.link,
    req.body.enabled,
    req.body.tags
  ];

  if (isBadRequest(values)) {
    res.status(400).send("Bad Request");
    return;
  }

  var query = 'INSERT INTO places ("country_id", "name", "description", "image", "latitude", "longitude", "link", "enabled") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING place_id';

  db.query(query, _.initial(values))
    .then(function(result) {
      var row = result.rows[0];
      var tags = _.last(values);
      var query = createTagQuery(row.place_id, tags);

      db.query(query)
        .then(function(result) {
          res.status(201).send(row);
        })
        .catch(function(error) {
          res.status(500).send(error);
        });
    })
    .catch(function(error) {
      res.status(500).send(error);
    });
});

router.put('/:id', function(req, res) {
  var values = [
    req.body.name,
    req.body.description,
    req.body.image,
    req.body.latitude,
    req.body.longitude,
    req.body.link,
    req.body.enabled
  ];

  if (isBadRequest(values)) {
    res.status(400).send("Bad Request");
    return;
  }

  var id = req.params.id;
  var tags = req.body.tags;
  var shouldUpdateTags = !(_.isUndefined(tags));

  var tagPromise = new Promise(function(resolve, reject) {
    if (shouldUpdateTags) {
      var tagResult = updateTags(id, tags);

      if (tagResult === true) {
        resolve("Done updating tags");
      } else {
        res.status(500).send(tagResult);
        reject("Failed updating tags");
        return;
      }
    } else {
      resolve("Not updating tags");
    }
  });

  tagPromise.then(function(result) {
    console.log(result);

    var query = "UPDATE places SET name = $1, description = $2, image = $3, latitude = $4, longitude = $5, link = $6, enabled = $7 WHERE place_id = " + id ;

    db.query(query, values)
    .then(function(result) {
      res.status(200).end();
    })
    .catch(function(error) {
      res.status(500).send(error);
    });
  });
});

module.exports = router;

@@ -508,467 +508,8 @@
 %7D;%0A%0A
-var updateTags = function(id, tags) %7B%0A  var tagQuery = 'DELETE FROM tags WHERE tags.place_id = $1';%0A  var tagValues = %5Bid%5D;%0A%0A  db.query(tagQuery, tagValues)%0A    .then(function(result) %7B%0A      tagQuery = createTagQuery(id, tags);%0A%0A      db.query(tagQuery)%0A        .then(function(result) %7B%0A          return true;%0A        %7D)%0A        .catch(function(error) %7B%0A          return error;%0A        %7D);%0A    %7D)%0A    .catch(function(error) %7B%0A      return error;%0A    %7D);%0A%7D;%0A%0A
 rout
@@ -2403,24 +2403,25 @@
 ject) %7B%0A
+%0A
     if (
 shouldUp
@@ -2412,16 +2412,17 @@
     if (
+!
 shouldUp
@@ -2443,130 +2443,187 @@
     
-var tagResult = updateTags(id,
+resolve(%22Not updating
  tags
+%22
 );%0A
-%0A      if (tagResult === true) %7B%0A        resolve(%22Done updating tags%22);%0A      %7D else
+    %7D else %7B%0A      var tagQuery = 'DELETE FROM tags WHERE tags.place_id = $1';%0A      var tagValues = %5Bid%5D;%0A%0A      var errorCallback = function(error)
  %7B%0A 
@@ -2654,17 +2654,13 @@
 end(
-tagResult
+error
 );%0A 
@@ -2677,41 +2677,153 @@
 ect(
-%22Failed updating
+error);%0A      %7D;%0A%0A      db.query(tagQuery, tagValues)%0A        .then(function(result) %7B%0A          tagQuery = createTagQuery(id,
  tags
-%22
 );%0A
+%0A  
         
 retu
@@ -2822,43 +2822,78 @@
     
-return;
+db.query(tagQuery)
 %0A      
-%7D%0A
+  
     
-%7D else %7B%0A
+.then(function(result) %7B%0A     
       
+   
 reso
@@ -2889,35 +2889,36 @@
        resolve(%22
-Not
+Done
  updating tags%22)
@@ -2915,24 +2915,116 @@
 ing tags%22);%0A
+            %7D)%0A            .catch(errorCallback);%0A        %7D)%0A        .catch(errorCallback);%0A
     %7D%0A  %7D);%0A

Fix async conditions of put method