const router = require('express').Router();
const co = require('co');
const toMongodb = require('jsonpatch-to-mongodb');

const dbX = require('../../db');

router.post('/', (req, res) => {
  if (!req.body) {
    return res.status(400).json({
      message: 'no data provided.'
    })
  }
  if (!req.body.vehicle || !req.body.patches) {
    return res.status(400).json({
      message: "insufficient parameters."
    })
  }

  // and other validations

  co(function*() {
    const db = yield dbX.dbPromise;
    const newVehicle = req.body.vehicle;
    const patches = {patches: req.body.patches};
    newVehicle.createdAt = (new Date()).toISOString();
    newVehicle.createdBy = req.user._id;
    patches.createdAt = (new Date()).toISOString();
    patches.createdBy = req.user._id;
    const patchResult = yield db.collection('vehiclePatches').insert(patches);
    const saveResult = yield db.collection('vehicles').insert(newVehicle);
    res.json(saveResult);
  }).catch(err => {
    if (err.stack && err.stack.indexOf('E11000') > -1) {
      return res.status(400).json(err.stack)
    }
    return res.status(500).json(err.stack);
  })

})

router.get('/', (req, res) => {
  co(function*() {
    const db = yield dbX.dbPromise;
    const docs = yield db.collection('vehicles').find({}, {
      'id': 1,
      'entranceDate': 1,
      'status': 1,
      'vehicle.plateNo': 1
    })
    .sort([['entranceDate', -1], ['_id', -1]])
    .toArray();
    res.send(docs);
  }).catch((err) => {
    return res.status(500).json(err.stack);
  })
  // return res.json(req.user);


})

router.get('/one', (req, res) => {
  if (!req.query.id) {
    return res.status(400).json({
      message: "insufficient parameters."
    })
  }
  co(function*() {
    const db = yield dbX.dbPromise;
    const docs = yield db.collection('vehicles').find({id: req.query.id}/*, {
      '_id': 0,
      'createdAt': 0,
      'createdBy': 0,
      'modifiedAt': 0,
      'modifiedBy': 0
    }*/).toArray();
    if (!docs.length) {return res.status(400).json({
      message: `no doc whose id is ${req.query.id}`
    })}
    const vehicle = docs[0];
    const userC = yield db.collection('users').find({_id: vehicle.createdBy}).toArray();
    const userM = yield db.collection('users').find({_id: vehicle.modifiedBy}).toArray();
    vehicle.createdBy = userC[0];
    vehicle.modifiedBy = userM[0];
    res.send(vehicle);
  }).catch((err) => {
    return res.status(500).json(err.stack);
  })
});

router.patch('/one', (req, res) => {
  if (!req.query.id) {
    return res.status(400).json({
      message: "insufficient parameters."
    })
  }
  if (!req.body) {
    return res.status(400).json({
      message: 'no data provided.'
    })
  }


  co(function*() {
    const db = yield dbX.dbPromise;
    const id = req.body.id;
    req.body.patches.push(
      {op: 'replace', path: '/modifiedAt', value: (new Date()).toISOString()},
      {op: 'replace', path: '/modifiedBy', value: req.user._id}
    )
    const patches = {patches: req.body.patches};
    patches.createdAt = (new Date()).toISOString();
    patches.createdBy = req.user._id;
    const patchesToApply = toMongodb(req.body.patches);
    const patchResult = yield db.collection('vehiclePatches').insert(patches);
    const updateResult = yield db.collection('vehicles').updateOne(
      {id},
      patchesToApply
    );
    res.json(updateResult);
    // console.log(patchesToApply);
    // res.json({
    //   message: 'ok'
    // })
  }).catch(err => {
    return res.status(500).json(err.stack);
  })

    // const updateResult = yield db.collection('tt').updateOne(
    //   {name: req.body.name}, 
    //   {$set: req.body},
    //   {upsert: true}
    // );
    // res.json(updateResult);


  // res.send({message: 'ok'});
  // co(function*() {
  //   const db = yield dbX.dbPromise;
  //   const docs = yield db.collection('vehicles').find({id: req.query.id}, {
  //     '_id': 0,
  //     'createdAt': 0,
  //     'createdBy': 0
  //   }).toArray();
  //   if (!docs.length) {return res.status(400).json({
  //     message: `no doc whose id is ${req.query.id}`
  //   })}
  //   res.send(docs[0]);
  // }).catch((err) => {
  //   return res.status(500).json(err.stack);
  // })
});
module.exports = router;
@@ -1296,24 +1296,40 @@
    'id': 1,%0A
+      'vin': 1,%0A
       'entra
@@ -1337,24 +1337,24 @@
 ceDate': 1,%0A
-
       'statu
@@ -1409,30 +1409,8 @@
 rt(%5B
-%5B'entranceDate', -1%5D, 
 %5B'_i
@@ -1608,34 +1608,35 @@
  if (!req.query.
-id
+vin
 ) %7B%0A    return r
@@ -1812,34 +1812,35 @@
 ehicles').find(%7B
-id
+vin
 : req.query.id%7D/
@@ -1835,18 +1835,19 @@
 q.query.
-id
+vin
 %7D/*, %7B%0A 
@@ -2066,26 +2066,27 @@
 $%7Breq.query.
-id
+vin
 %7D%60%0A    %7D)%7D%0A 
@@ -2503,25 +2503,45 @@
 %7B%0A  
-if (!req.query.id
+const vin = req.query.vin;%0A  if (!vin
 ) %7B%0A
@@ -2787,36 +2787,8 @@
 se;%0A
-    const id = req.body.id;%0A
     
@@ -3308,18 +3308,19 @@
 %0A      %7B
-id
+vin
 %7D,%0A     
@@ -3884,18 +3884,19 @@
 q.query.
-id
+vin
 %7D, %7B%0A  /
@@ -4087,18 +4087,19 @@
 q.query.
-id
+vin
 %7D%60%0A  // 

rename vehicle.id to vehicle.vin