'use strict';

/*
 * Vendor modules
 */
let express = require('express');
let router = express.Router();

/**
 * Custom modules
 */
let log = require('./../../helpers/log');
let presetModel = require('./../../models/preset.model');

// Delete user preset
router.delete('/', (req, res) => {
  presetModel.delete(req.param("presetId"), req.userId)
    .then(function () {
      res.json({message: "Presets deleted"});
    })
    .catch(function (err) {
      log.error(err);
      res.status(422).json({error: "Failed to delete preset"});
    })
});

// Get a list of user presets
router.get('/', (req, res) => {
  presetModel.findByUser(req.userId)
    .then(function (data) {
      res.json({message: "Presets list", data: data});
    })
    .catch(function (err) {
      log.error(err);
      res.status(422).json({error: "No presets"});
    })
});

// Create new preset (name, order)
router.post('/', (req, res) => {

  console.log(req.body);

  if (!req.body.presetId) {
    presetModel.create(req.body.name, req.body.order, req.body.color, req.userId)
      .then(function (data) {
        res.json({
          message: "Preset '" + data.name + "' created.",
          data: data
        })
      })
      .catch(function (err) {
        log.error(err);
        res.status(422).json({error: err.message});
      });
  } else if (req.body.presetId !== "") {
    presetModel.update(req.body.presetId, req.userId, req.body.name, req.body.color)
      .then(function (data) {
        presetModel.findById(data._id)
          .then(function (data) {
            res.json({message: "Presets updated", data: data});
          })
          .catch(function (err) {
            log.error(err);
            res.status(422).json({error: "No presets"});
          })
      })
      .catch(function (err) {
        log.error(err);
        res.status(422).json({error: err.message});
      });
  }
});

router.post('/order', (req, res) => {
  if (req.body.presets) {
    presetModel.reOder(req.body.presets, req.userId);
    res.json({message: "Presets reordered"})
  } else {
    res.json({message: "No data"})
  }
});

module.exports = router;
