const Sequelize = require('sequelize');
const express = require("express");
const bodyParser = require("body-parser");
// const cors = require('cors')
require('dotenv').config({ path: '.env.local' });

const database = new Sequelize({
  dialect: 'sqlite',
  storage: './xmas.sqlite',
});

const Attendee = database.define('attendee', {
  name: Sequelize.STRING,
  guest: Sequelize.BOOLEAN,
  superhero: Sequelize.STRING
});

const whitelist = ['http://localhost:3001', 'http://localhost', 'http://127.0.0.1', 'http://christmas.logicp.ca']

// const corsOptions = {
//   origin: function (origin, callback) {
//     console.log('request attempted from ', origin)
//     if (whitelist.indexOf(origin) !== -1) {
//       callback(null, true)
//     } else {
//       callback(new Error('Not allowed by CORS'))
//     }
//   }
// }

class App {
    //Run configuration methods on the Express instance.
    constructor() {
        this.express = express();
        this.middleware();
        this.routes();
    }
    // Configure Express middleware.
    middleware() {
        // this.express.use(logger('dev'));
        this.express.use(bodyParser.json());
        this.express.use(bodyParser.urlencoded({ extended: true }));
        // this.express.engine('html', require('ejs').renderFile);
    }
    // Configure API endpoints.
    routes() {
        /* This is just to get up and running, and to make sure what we've got is
         * working so far. This function will change when we start to add more
         * API endpoints */
        this.express.get('/test', (req, res) => {
          console.log(req)
          res.json({response: 'yo mamma'})
        })

        this.express.get('/list', (req, res) => {
          Attendee.findAll().then(attendees => {
            res.json({attendees: attendees})
          })
        })

        this.express.post('/attendee', (req, res) => {
          console.log(req.body)
          if ('name' in req.body) {
            Attendee.findOrCreate({
              where: {
                name: req.body.name
              }
            })
            .spread( attendee => {
              console.log(attendee)
              attendee.guest = req.body.significantOther
              attendee.superhero = req.body.superhero
              Attendee.update({
                name: req.body.name,
                superhero: req.body.superhero,
                guest: req.body.significantOther
              }, {
                where: {
                  id: attendee.id
                }
              }).then( attendee => {
                console.log('Successfully updated attendee:', attendee)
                res.json({response: 'success', code: 200, error: false})
              })
            })
          }
        })
    }
}

const app = new App().express

app.listen(3002)
 app.options('/attendee', function (req, res) {
   res.setHeader("Access-Control-Allow-Origin", whitelist.join('|'));
   res.setHeader('Access-Control-Allow-Methods', '*');
   res.setHeader("Access-Control-Allow-Headers", "*");
   res.end();
});

 app.all('*', function(req, res, next) {
   if (whitelist.indexOf(req.headers.origin) >= 0){
       res.header("Access-Control-Allow-Origin", req.headers.origin);
   }
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
 })

database.sync().then(() => {
    console.log(`Listening on port ${3002}`);
});
