// coinRoutes.js

var express = require('express');
var jobRoutes = express.Router(); //set

// Require Item model in our routes module
var Job = require('../models/Job'); //set

// Defined store route
jobRoutes.route('/add').post(function (req, res) { //set
  var job = new Job(req.body); //set
   job.save() //set
    .then(item => {
    res.status(200).json({'job': 'job added successfully'}); //set
    })
    .catch(err => {
    res.status(400).send("unable to save to database"); 
    });
});

// Defined get data(index or listing) route
jobRoutes.route('/').get(function (req, res) { //set
   Job.find(function (err, jobs){ //set
    if(err){
      console.log(err);
    }
    else {
      res.json(jobs); //set
    }
  });
});

// Defined edit route
jobRoutes.route('/edit/:id').get(function (req, res) { //set
  var id = req.params.id;
  Job.findById(id, function (err, job){ //set
      res.json(job); //set
  });
});

//  Defined update route
jobRoutes.route('/update/:id').post(function (req, res) { 
  Job.findById(req.params.id, function(err, job) { 
   if (!job) //set
     return next(new Error('Could not load Document'));
   else { //set
     job.topic = req.body.topic;
     job.date = req.body.date;
     job.story = req.body.story;
     

     job.save().then(job => { 
         res.json('Update complete');
     })
     .catch(err => {
           res.status(400).send("unable to update the database");
     });
   }
 });
});

// Defined delete | remove | destroy route
jobRoutes.route('/delete/:id').get(function (req, res) { //set
   Job.findByIdAndRemove({_id: req.params.id}, function(err, job){ //set
        if(err) res.json(err);
        else res.json('Successfully removed');
    });
});

module.exports = jobRoutes; //set
