

require('dotenv').load()
const utils = require('./src/utils');
const mailer = require("./src/mailer.js")
const { google } = require('googleapis');
//const express = require('express')
const axios = require('axios')
const next = require('next')
const nextAuth = require('next-auth')
const nextAuthConfig = require('./next-auth.config')
const { join } = require('path');
const { parse } = require('url');

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

// const passport = require('passport')
// const FacebookStrategy = require('passport-facebook').Strategy

const routes = {
  admin: require('./routes/admin'),
  account: require('./routes/account')
}

const bodyParser = require('body-parser');

function getAccessToken() {
  return new Promise(function (resolve, reject) {
    var key = require('./service-account.json');
    var jwtClient = new google.auth.JWT(
      key.client_email,
      null,
      key.private_key,
      'https://www.googleapis.com/auth/firebase.messaging',
      null
    );
    jwtClient.authorize(function (err, tokens) {
      if (err) {
        reject(err);
        return;
      }

      resolve(tokens.access_token);
    });
  });
}

// passport.use(new FacebookStrategy({
//   clientID: process.env.FACEBOOK_ID,
//   clientSecret: process.env.FACEBOOK_SECRET,
//   callbackURL: "http://localhost:3000/auth/facebook/callback",
//   enableProof: true
// },
//   function (accessToken, refreshToken, profile, cb) {
//     User.findOrCreate({ facebookId: profile.id }, function (err, user) {
//       return cb(err, user);
//     });
//     console.log(profile)

//     console.log("accessToken : " + accessToken);
//     console.log("refreshToken" + refreshToken);//****not needed because we only use accesstoken to connect to our api*/

//     return cb(null, profile);
//   }
// ));

app.prepare()
  .then(() => {
    // Load configuration and return config object
    return nextAuthConfig()
  })
  .then(nextAuthOptions => {
    // Pass Next.js App instance and NextAuth options to NextAuth
    // Note We do not pass a port in nextAuthOptions, because we want to add some
    // additional routes before Express starts (if you do pass a port, NextAuth
    // tells NextApp to handle default routing and starts Express automatically).
    return nextAuth(app, nextAuthOptions)
  })
  .then(nextAuthOptions => {

    const express = nextAuthOptions.express
    const expressApp = nextAuthOptions.expressApp

    // Add admin routes
    routes.admin(expressApp)

    // Add account management route - reuses functions defined for NextAuth
    routes.account(expressApp, nextAuthOptions.functions)

    expressApp.use('/', express.static(__dirname + '/.next/'))

    var jsonParser = bodyParser.json()

    expressApp.post('/feedback', jsonParser, (req, res) => {

      let message = req.body.message;
      let nom = req.body.nom;
      let prenom = req.body.prenom;
      let tel = req.body.tel;
      let mail = req.body.mail;
      let recaptchaValue = req.body.recaptchaValue;

      console.log(message);
      if (message === '') {
        res.status(400).json({
          errors: { global: "Message is empty." }
        }); return;
      }
      if (mail === '') {
        res.status(400).json({
          errors: { global: "email is empty." }
        }); return;
      }
      utils.verifyCaptcha(recaptchaValue)
        .then(
          respo => {
            if (respo.data.success == true) {
              try {
                mailer.sendEmail(message, nom, prenom, tel, mail);
                res.status(200).send({})
              } catch (err) {
                res.status(500).send({ message: "Send mail fail." })
              }
            }
            else
              res.status(500).send({ message: "Captcha invalid." })
          })
        .catch(() =>
          res.status(403).send({ message: "Captcha verification impossible." })
        )

    });

    expressApp.post('/push/message', jsonParser, (req, res) => {
      let message = req.body.payload;

      if (message === '') {
        res.status(400).json({
          errors: { global: "Message is empty." }
        }); return;
      }
      else {
        getAccessToken().then((googleAccessToken) => {
          utils.setAuthorizationHeader(googleAccessToken);
          // console.log(message);
          axios.post('https://fcm.googleapis.com/v1/projects/edeclicpwa/messages:send',
            message
          ).then(r => {
            console.log("message : "); console.log(r)
            res.status(200).send({ message: "message sent to firebase" })
          }
          )
            .catch(err => console.log("first catch" + err)
              //res.status(500).send({ message: "Push error" })
            )
        }).catch(err => console.log("second catch" + err)
          //err => res.status(500).send({ message: "Push error" + err })
        )

      }
    })

    expressApp.get('/push/info/:token', (req, res) => {

      var token = req.params.token
      if (token === '') {
        res.status(498).json({
          errors: { global: "No token specified." }
        }); return;
      }

      var url = 'https://iid.googleapis.com/iid/info/' + token + '?details=true'

      utils.setAuthorizationHeaderForIID(process.env.FIREBASE_API_KEY)
      axios.get(url).then(r => {
        if (!!r.data.rel && !!r.data.rel.topics) {
          res.status(200).send({ topics: r.data.rel.topics })
        }
        else
          res.status(200).send({ topics: null })
      }).catch(err => {
        console.log(err)
        res.status(500).send({ message: "Push error" })
      })

    })

    expressApp.post('/push/subscribe', jsonParser, (req, res) => {
      let message = req.body;

      if (message === '') {
        res.status(400).json({
          errors: { global: "Message is empty." }
        }); return;
      }
      else {
        if (message.topic === '' || message.token === '') {
          res.status(400).json({
            errors: { global: "Message isnot well formed." }
          }); return;
        }

        var url = 'https://iid.googleapis.com/iid/v1/' + message.token + '/rel/topics/' + message.topic

        utils.setAuthorizationHeaderForIID(process.env.FIREBASE_API_KEY)

        axios.post(url)
          .then(r => {
            res.status(200).send({ message: "message sent to firebase" })
          })
          .catch(err => console.log(err))

      }
    })

    expressApp.post('/push/unsubscribe', jsonParser, (req, res) => {
      let message = req.body;

      if (message === '') {
        res.status(400).json({
          errors: { global: "Message is empty." }
        }); return;
      }
      else {
        if (message.topic === '' || message.token === '') {
          res.status(400).json({
            errors: { global: "Message is not well formed." }
          }); return;
        }
        message.topic = '/topics/' + message.topic
        var payload = { to: message.topic, registration_tokens: [message.token] }
        var url = 'https://iid.googleapis.com/iid/v1:batchRemove'

        utils.setAuthorizationHeaderForIID(process.env.FIREBASE_API_KEY)
        axios.post(url, payload
        ).then(r => {
          res.status(200).send({ message: "message sent to firebase" })
        }
        )
          .catch(err => console.log(err)
          )
      }
    })

    //https://us-central1-edeclicpwa.cloudfunctions.net/pushMessageToAllSubscribers
    expressApp.post('/push/allsubscribers', jsonParser, (req, res) => {
      let message = req.body.payload;

      if (message === '') {
        res.status(400).json({
          errors: { global: "Message is empty." }
        }); return;
      }
      else {

        utils.setAuthorizationHeader(process.env.FIREBASE_API_KEY)
        // console.log(message);
        axios.post('https://us-central1-edeclicpwa.cloudfunctions.net/pushMessageToAllSubscribers',
          { payload: message }
        ).then(r => {
          res.status(200).send({ message: "message sent to firebase" })
        }
        )
          .catch(err => console.log(err))

      }
    })

    expressApp.get('/static/js/*.js', (req, res) => {

      const parsedUrl = parse(req.url, true);
      const { pathname } = parsedUrl;
      const filePath = join(__dirname, '.next', pathname);
      app.serveStatic(req, res, filePath);
    })

    expressApp.get('/manifest.json', (req, res) => {

      const parsedUrl = parse(req.url, true);
      const { pathname } = parsedUrl;
      const filePath = join(__dirname, '/static/', pathname);
      app.serveStatic(req, res, filePath);
    })

    expressApp.get('*', (req, res) => {
      return handle(req, res)
    })

    expressApp.listen(process.env.PORT, (err) => {
      if (err) throw err
      console.log('> Ready on http://localhost:' + process.env.PORT)
      console.log('> access Token googleapi >' + getAccessToken())
    })
  })
  .catch((ex) => {
    console.error(ex.stack)
    process.exit(1)
  })