const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Subscription = mongoose.model('subscribers');

const tools = require('../tools/general');

var { authenticate } = require('../middleware/authenticate');

const isValidSaveRequest = (req, res) => {
  try {
    if (!req.body || !req.body.subs.endpoint) {
      res.status(400);
      res.setHeader('Content-Type', 'application/json');
      res.send(JSON.stringify({
        error: {
          id: 'no-endpoint',
          message: 'Subscription must have an endpoint'
        }
      }));
      return false
    }
    return true
  } catch (e) {
    return false
  }
};

router.post('/', authenticate, (req, res) => {
  // console.log('req.body.others', req.body.others);

  if (!isValidSaveRequest(req, res)) {
    return;
  }

  let subscriptionModel = new Subscription(req.body.subs);
  subscriptionModel.userId = req.body.others.userId;
  subscriptionModel.access = req.body.others.access;
  subscriptionModel.browser = req.get('User-Agent');

  // Find if already exist
  Subscription.findOne( {userId: subscriptionModel.userId, access: subscriptionModel.access, browser: subscriptionModel.browser})
    .then(itemsub => {
       return itemsub
    })
    .catch(err => {
      // Not found
      return null
    })
    .then(myitem => {

      if (myitem === null) {
        myitem = subscriptionModel;
        tools.mylogshow('Subscription NOT EXISTED IN DB, so I use this created!', myitem)
      }

      // else
      //   tools.mylogshow('Subscription already Existed!');


      myitem.save((err, subscription) => {
        if (err) {
          console.error(`Error occurred while saving subscription. Err: ${err}`);
          res.status(500).json({
            error: 'Technical error occurred'
          });
        } else {
          // Send 201 - resource created
          // res.status(201).json({ data: 'Subscription saved.' });
          res.send({ data: 'Subscription saved.' });

          if (req.body.options !== null) {
            tools.sendBackNotif(subscription, req.body.options)
          }
        }
      });
    });

});


router.delete('/del', authenticate, (req, res) => {
  // tools.mylog("TOKENREM = " + req.token);
  const browser = req.get('User-Agent');
  Subscription.findOneAndRemove( { userId: req.user._id, access: req.access, browser } ).then(() => {
    res.status(200).send();
  }, () => {
    res.status(400).send();
  });
});



router.get('/', (req, res) => {
  res.json({
    data: 'Invalid Request Bad'
  });
});

module.exports = router;
