const express = require('express');
const router = express.Router();
const mongoose = require('mongoose').set('debug', false);
const Subscription = require('../models/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, async (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');
  subscriptionModel.browser_random = req.body.others.browser_random;

  // console.log('subscriptionModel.browser', subscriptionModel.browser);

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

    if (myitem === null) {
      myitem = subscriptionModel;
      // tools.mylogshow('Subscription NOT EXISTED IN DB, so I use this created!')
    } else {
      myitem.endpoint = subscriptionModel.endpoint;
      myitem.keys = subscriptionModel.keys;
      myitem.createDate = new Date();
    }

    try {
      const subscription = await myitem.save();

      // Send 201 - resource created
      // res.status(201).json({ data: 'Subscription saved.' });

      // console.log('New Subscription id=', subscriptionModel.userId);

      // console.log('req.body', req.body)

      if (req.body.options !== null) {
        // Invia una notifica PUSH (asincrona)
        tools.sendBackNotif(subscription, req.body.options);
      }
      // console.log('Subscription saved... ')
      return res.send({ data: 'Subscription saved.' });

      return subscription;

    } catch (err) {
      console.error(`Error occurred while saving subscription. Err: ${err}`);
      return res.status(500).json({
        error: 'Technical error occurred',
      });
    }

  });
});

router.delete('/del', authenticate, async (req, res) => {
  // tools.mylog("TOKENREM = " + req.token);
  try {

    if (req.user) {
      const browser = req.get('User-Agent');
      const browser_random = req.body.browser_random;
      return await Subscription.findOneAndDelete(
        { userId: req.user._id, access: req.access, browser, browser_random }).then(() => {
          res.status(200).send();
        }, () => {
          res.status(400).send();
        });
    }
    res.status(400).send();
  } catch (e) {
    console.error('Err:', e.message);
  }
});

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

module.exports = router;
