const Sequelize = require('sequelize');
const sequelize = new Sequelize('mysql://alex:alex88003@localhost:3306/crossmap_dev', {
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
});
const express = require("express");
const bodyParser = require('body-parser');

sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });


class Comment extends Sequelize.Model { }
Comment.init({
  commentID: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  postID: Sequelize.INTEGER,
  userID: Sequelize.INTEGER,
  parentID: Sequelize.INTEGER,
  comment: Sequelize.STRING,
  like_count: Sequelize.INTEGER,
  bad_count: Sequelize.INTEGER,
  datePosted: Sequelize.DATE,
  dateUpdated: Sequelize.DATE,
  dateDeleted: Sequelize.DATE
}, { sequelize, modelName: 'cm_comment', freezeTableName: true, timestamps: false });


var app = express();
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());
app.listen(20002, () => {
  console.log("Server running on port 20002");
});


/**
 * Encrypts a password using sha256 and a salt value.
 *
 * @param password The password to hash.
 * @param salt The salt value to hash with.
 */
function SHA256Encrypt(password, salt) {
  var saltedpassword = salt + password;
  var sha256 = crypto.createHash('sha256');
  sha256.update(saltedpassword);
  return sha256.digest('base64');
}

/**
* Validates a password sent by an end user by comparing it to the
* hashed password stored in the database.
*
* @param password The password sent by the end user.
* @param dbPassword The hashed password stored in the database, encoded in Base64.
* @param dbSalt The encryption salt stored in the database. This should be a raw blob.
*/
function validatePassword(password, dbPassword, dbSalt) {
  var hashed = SHA256Encrypt(password, dbSalt.toString('binary'));
  return hashed === dbPassword;
}


app.get('/v1/comments/:siteKey/:postID', (req, res, next) => {
  var siteKey = req.params.siteKey;
  Comment.findAll({ where: { postID: req.params.postID } }).then(comment => {
    res.json(comment);
  })
})

app.put('/v1/comment/:commentID', (req, res, next) => {
  console.log(req.body)
  Comment.update(
    {
      comment: req.body.comment,
    },
    {
      where: {
        commentID: req.params.commentID
      }
    }
  ).then(updated => {
    res.json({
      code: 200
    });
  });
})

app.delete('/comment', (req, res, next) => {
  Comment.update(
    {
      dateDeleted: Date.now(),
    },
    {
      where: {
        commentID: req.params.commentID
      }
    }
  ).then(updated => {
    res.json({
      code: 200
    });
  });

})

app.post('/comment', (req, res, next) => {
  Comment.findOne({ where: { commentID: 1 } }).then(comment => {
    res.json(comment);
  })
})


