import express from 'express'
import {check_authentication, validate_request} from '../utils/errors'
import {counter_model} from '../models/counter_model'

const all_counters_router = express.Router()
all_counters_router.param('group_id', (request, response, next_handler) => {
  request.checkParams('group_id', 'parameter is required').notEmpty()
  request
    .checkParams('group_id', 'parameter must be a MongoDB ObjectId')
    .isMongoId()

  validate_request(request, next_handler)
})
all_counters_router.route('/groups/:group_id/counters')
  .get(check_authentication, (request, response, next_handler) => {
    request
      .checkQuery(
        'start_timestamp',
        'parameter must be a timestamp in the ISO 8601 format'
      )
      .optional()
      .isDate()
    request.sanitizeQuery('start_timestamp').toDate()

    validate_request(request, next_handler)
  }, (request, response, next_handler) => {
    const query = {
      group_id: request.params.group_id,
    }
    if (request.query.start_timestamp instanceof Date) {
      query.timestamp = {
        $gte: request.query.start_timestamp,
      }
    }

    counter_model
      .find(query)
      .sort({
        timestamp: 'descending',
      })
      .then(counters => response.json({
        data: counters,
      }))
      .catch(next_handler)
  })
  .post(check_authentication, (request, response, next_handler) => {
    counter_model
      .create({
        group_id: request.params.group_id,
        value: Math.round(1000 * Math.random()),
      })
      .then(counter => response.json({
        data: counter,
      }))
      .catch(next_handler)
  })
  .delete(check_authentication, (request, response, next_handler) => {
    counter_model
      .remove({
        group_id: request.params.group_id,
      })
      .then(() => response.json({
        data: true,
      }))
      .catch(next_handler)
  })

export const counter_router = express.Router()
counter_router.use(all_counters_router)

@@ -147,16 +147,66 @@
 r_model'
+%0Aimport %7Bgroup_model%7D from '../models/group_model'
 %0A%0Aconst 
@@ -1437,39 +1437,37 @@
 ndler) =%3E %7B%0A    
-counter
+group
 _model%0A      .cr
@@ -1468,35 +1468,17 @@
    .
-create(%7B%0A        group_id: 
+findById(
 requ
@@ -1500,90 +1500,169 @@
 p_id
-,
+)
 %0A      
-  value: Math.round(1000 * Math.random()),%0A      %7D)%0A      .then(counter =%3E
+.then(group =%3E group.update_counter((error, counter) =%3E %7B%0A        if (error !== null) %7B%0A          next_handler(error)%0A          return%0A        %7D%0A%0A       
  res
@@ -1674,32 +1674,34 @@
 .json(%7B%0A        
+  
 data: counter,%0A 
@@ -1699,16 +1699,27 @@
 ounter,%0A
+        %7D)%0A
       %7D)

Correct a creation of counters