// vim: set ts=2 sw=2 et tw=80:

const debug = require('debug')('canvas-server');
const express = require('express');
const path = require('path');
const logger = require('morgan');
const bodyParser = require('body-parser');
const kleiDust = require('klei-dust');
const methodOverride = require('method-override');
const fs = require('fs');

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/SA3_hw6', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

require('./models/Favorites');

const app = express();

//configure app
app.use(logger('dev'));
app.set('views', __dirname + '/views');
app.engine('dust', kleiDust.dust);
app.set('view engine', 'dust');
app.set('view options', { layout: false });

app.use(methodOverride('_method'));

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false, limit: '50mb' }));

// parse application/json
app.use(bodyParser.json({ limit: '50mb' }));

// Needed to make fetch_tests passs
app.use(bodyParser.text({ type: '*/*', limit: '50mb' }));

app.use(express.static('public'));

// Initialize routers here
const routers = require('./routes/routers');

app.use('/', routers.root);
// app.use('/favorites', routers.favourites_db);
// app.use('/favorites', routers.favourites_db_promises);
app.use('/favorites', routers.favourites_db_asaw);
app.use('/bookmarked', routers.bookmarked);
app.use('/test/fetch', routers.fetch_tests);

app.set('port', process.env.PORT || 3000);
const server = app.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
});

// Socket.io code

const io = require('socket.io')(server);

let id = 1;

io.on('connection', (socket) => {
  console.log('client connected');

  socket.emit('sessionId', { id: id++ });

  socket.on('message', (msg) => {
    console.log('message: ',msg);
    msg.user = encodeURIComponent(msg.user);
    msg.text = encodeURIComponent(msg.text);
    socket.broadcast.emit('message', msg);
  });

  socket.on('disconnect', () => {
    console.log('client disconnected');
  });
});

const eventBus = require('./pubsub');

eventBus.on('favorite.created', (event) => {
  io.emit('favorite.created', event);
});
eventBus.on('favorite.updated', (event) => {
  io.emit('favorite.updated', event);
});
eventBus.on('favorite.deleted', (event) => {
  io.emit('favorite.deleted', event);
});

const { exec } = require('child_process');
const client = '3710c666dbec94e';
const imgURL = `https://api.imgur.com/oauth2/authorize?client_id=${client}` +
  "&response_type=token";

exec(`open '${imgURL}' || xdg-open ${imgURL}`, (err) => {
  if (err) {
    console.error(err);
  }
});

module.exports = app;
