import path from 'path';
import util from 'util';
import { default as express } from 'express';
import { default as passport } from 'passport';
import { default as passportLocal } from 'passport-local';
const EstrategiaLocal = passportLocal.Strategy;
import * as modeloUsers from '../models/users-admin.mjs';
import { sesionCookie } from '../app.mjs';
import passportTwitter from 'passport-twitter';
const EstrategiaTwitter = passportTwitter.Strategy;
import DBG from 'debug';
const debug=DBG('notas:router-users');
const error=DBG('notas:error-users');

export const router = express.Router();

export function iniciaPass(app) {
        app.use(passport.initialize());
        app.use(passport.session());
}

export function validaAutenticado(req, res, next) {
        try {
                if (req.user) next();
                else res.redirect('/users/login');
        } catch(e) { next(e); }
}

router.get('/login', function(req, res, next) {
        try {
                res.render('login', { title: 'Ingreso a Notas',
                        user: req.user });
        } catch(e) { next(e); }
});

router.post('/login',
        passport.authenticate('local', {
                successRedirect: '/',
                failureRedirect: 'login'
        })
);

router.get('/logout', function(req, res, next) {
        try {
                req.session.destroy();
                req.logout();
                res.clearCookie(sesionCookie);
                res.redirect('/');
        } catch(e) { next(e); }
});

passport.use(new EstrategiaLocal({
                usernameField: 'usuario',
                passwordField: 'clave'
        },
        async (usuario, clave, done) => {
                try {
                        var chk = await modeloUsers.chequeaClave(usuario,
                                        clave);
                        if (chk.check) {
                                done(null, {
                                        id: chk.usuario,
                                        usuario: chk.usuario
                                });
                        } else {
                                done(null, false, chk.message);
                        }
                } catch(e) { done(e); }
        }
));

passport.serializeUser(function(user, done) {
        try {
                console.log("Serial");
                done(null, user.usuario);
        } catch(e) { done(e); }
});

passport.deserializeUser(async (usuario, done) => {
        try {
                var user = await modeloUsers.buscar(usuario);
                done(null, user);
        } catch(e) { done(e); }
});

const twtcallback = process.env.TWITTER_CALLBACK_HOST
		? process.env.TWITTER_CALLBACK_HOST
		: "http://localhost:3000";
export var twtLogin;

if (typeof process.env.TWITTER_CONSUMER_KEY !== 'undefined'
	&& process.env.TWITTER_CONSUMER_KEY !==''
	&& typeof process.env.TWITTER_CONSUMER_SECRET !=='undefined'
	&& process.env.TWITTER_CONSUMER_SECRET !=='') {
	passport.use(new EstrategiaTwitter({
		consumerKey: process.env.TWITTER_CONSUMER_KEY,
		consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
		callbackURL: `${twtcallback}/users/auth/twitter/callback`
	},
		async function(token, tokenSecret, profile, done) {
			try {
			  done(null, await modeloUsers.buscarCrear({
				id: profile.username,
				usuario: profile.username,
				clave: "",
				proveedor: profile.provider,
				apellido: profile.displayName,
				nombre: "", email: profile.emails,
				foto: profile.photos
		   	  }));
			} catch(err) { done(err); }
	}));

	twtLogin = true;
} else {
	twtLogin = false;
}

router.get('/auth/twitter', passport.authenticate('twitter'));

router.get('/auth/twitter/callback',
		passport.authenticate('twitter', {
			successRedirect: '/',
			failureRedirect: '/users/login' 
		}));
