const EventEmitter = require('events');
const Express = require('express');
const ResetModel = require('../models/reset');
const Router = Express.Router();
const Token = require('../modules/token');

Router.route('/login')
  .post((req, res, next) => {
		var AuthEvents = new EventEmitter();
		var data = req.body;
		var headers = req.headers;
		
		AuthEvents.once('authenticateUser', (err, result) => {
      console.log('[AuthRoute::POST::/auth/login] User Authenticated', { err: err, result: result });

			login = result || {};
			login.status = result.status || 500;


			if (err) {
				login.err = err;
				res.status(login.status).json(login);
			}
			
			if (login) {
				// Authenticated - create session
				if (login.authorized) {
					var TokenEvents = new EventEmitter();
				
					TokenEvents.once('token:create', (err, token) => {
						if (err) {
							login = {
								status: 500,
								authorized: false,
								err: err
							};
						}
					
						if (token) {
							login.token = token;
							res.status(login.status).json(login);
						}
					});
					
					Token.create(TokenEvents, login.user);
				}
				// Authentication failed
				else {
					res.status(login.status).json(login);
				}
			}
		});
		
		UserModel.authenticateUser(AuthEvents, data, headers);
	});
	
Router.route('/secure/:auth/:expires?')
	.get((req, res) => {
    if (req.params.auth === 'gutenberg') {
      let TokenEvents = new EventEmitter();
      let expires = req.params.expires || '15m';
      let token = { username: 'apiuser', can: ['add','edit','delete','manage','super','update','view'] };
    
      TokenEvents.once('token:create', (err, token) => {
        if (err) {
          res.status(500).json({
            authorized: false,
            err: err
          });
        }
      
        if (token) {
          res.status(200).json({
            authorized: true,
            token: token
          });
        }
      });
      
      Token.create(TokenEvents, token, expires);
    } else {
      res.status(403).json({ authorized: false, message: 'operation not authorized' });
    }	
	});
	
Router.route('/reset/:id?/:token?')
  .get((req, res) => {
    var id = req.params.id ? decodeURIComponent(req.params.id) : false;
    var token = req.params.token ? decodeURIComponent(req.params.token) : false;
    var ResetEvents = new EventEmitter();
    
    ResetEvents.once('checkReset', (err, result) => {
			if (err) {
				res.status(500).json({ message: 'There was an error validating the password reset', err: err });
			}
			
			if (result) {
				res.status(200).json(result);
			}		
    });
    
    ResetModel.checkReset(ResetEvents, id, token);
  })
  .post((req, res) => {
    var username = req.body.username;
    var ResetEvents = new EventEmitter();
    
    ResetEvents.once('sendReset', (err, result) => {
			if (err) {
			  console.log('[routes/auth::sendReset] Error: ', { err: err });
				res.status(500).json({ message: 'There was an error requesting the password reset', err: err });
			}
			
			if (result) {
			  console.log('[routes/auth::sendReset] Success: ', { result: result });
				res.status(200).json(result);
			}		
    });
    
    UserModel.findUser({ userName: username }, (err, user) => {
      ResetModel.sendReset(ResetEvents, user);
    });
  })
  .put((req, res) => {
    var id = req.params.id ? decodeURIComponent(req.params.id) : false;
    var token = req.params.token ? decodeURIComponent(req.params.token) : false;
    var data = req.body;
    var UserEvents = new EventEmitter();

    UserEvents.once('updatePassword', (err, result) => {
      if (err) {
        res.status(500).json({ message: err.message, err: err });
      }
    
      if (result) {
        res.status(200).json(result);
      }		
    });

    UserModel.updatePassword(UserEvents, id, token, data);
  });
  
Router.route('/session')
  .get((req, res) => {
    var AuthEvents = new EventEmitter();
    var token = req.get('authorization');
  
    AuthEvents.once('token:validate', (err, result) => {
      if (err) {
        res.status(500).json({ message: 'There was an error validating the token', err: err });
      }
    
      if (result) {
        res.status(200).json(result);
      }		
    });

    Token.validate(AuthEvents, token);
  })
  .post((req, res) => {
    var AuthEvents = new EventEmitter();
  
    AuthEvents.once('token:create', (err, token) => {
      if (err) {
        res.status(500).json({ 
          status: 500,
          authorized: false,
          err: err 
        });
      }
    
      if (token) {
        res.status(200).json({
          status: 200,
          authorized: false,
          token: token
        });
      }		
    });

    Token.anonymous(AuthEvents);
  })
  .put((req, res) => {
    var AuthEvents = new EventEmitter();
    var token = req.get('authorization');
  
    AuthEvents.once('token:refresh', (err, token) => {
      if (err) {
        res.status(500).json({ message: 'There was an error refreshing the token', err: err });
      }
    
      if (token) {
        res.status(200).json(token);
      }		
    });

    Token.refresh(AuthEvents, token);
  });

module.exports = Router;
