import Sequelize from 'sequelize';
import { default as jsyaml } from 'js-yaml';
import { promises as fs } from 'fs';
import * as util from 'util';
import DBG from 'debug';
const log = DBG('users:model-users');
const error = DBG('users:error');

var sequelz;

export class SQUser extends Sequelize.Model {}

export async function conectarDB() {
	if (sequelz) return sequelz;

	const textoyaml = await fs.readFile(process.env.SEQUELIZE_CONNECT,
						'utf8');
	const params = await jsyaml.safeLoad(textoyaml, 'utf8');

	if (typeof process.env.SEQUELIZE_BASE !== 'undefined'
		&& process.env.SEQUELIZE_BASE !== '') {
		params.dbname = process.env.SEQUELIZE_BASE;
	}

        if (typeof process.env.SEQUELIZE_USUARIO !== 'undefined'
                && process.env.SEQUELIZE_USUARIO !== '') {
                params.username = process.env.SEQUELIZE_USUARIO;
        }

        if (typeof process.env.SEQUELIZE_CLAVE !== 'undefined'
                && process.env.SEQUELIZE_CLAVE !== '') {
                params.password = process.env.SEQUELIZE_CLAVE;
        }

        if (typeof process.env.SEQUELIZE_HOST !== 'undefined'
                && process.env.SEQUELIZE_HOST !== '') {
                params.host = process.env.SEQUELIZE_HOST;
        }

        if (typeof process.env.SEQUELIZE_PORT !== 'undefined'
                && process.env.SEQUELIZE_PORT !== '') {
                params.port = process.env.SEQUELIZE_PORT;
        }

        if (typeof process.env.SEQUELIZE_DIALECT !== 'undefined'
                && process.env.SEQUELIZE_DIALECT !== '') {
                params.dialect = process.env.SEQUELIZE_DIALECT;
        }

	log('Parametros Sequelize ' + util.inspect(params));

	sequelz = new Sequelize(params.dbname, 
				params.username,
				params.password, {
				dialect: params.dialect,
				storage: params.storage,
				port: params.port,
				host: params.host
				});

	SQUser.init({
		usuario: { type: Sequelize.STRING, unique: true },
		clave: Sequelize.STRING,
		proveedor: Sequelize.STRING,
		apellido: Sequelize.STRING,
		nombre: Sequelize.STRING,
		email: Sequelize.STRING(2048),
		foto: Sequelize.STRING(2048)
	}, {
		sequelize: sequelz,
		modelName: 'SQUser'
	});
	await SQUser.sync();
}

export function paramsUser(req) {
	return {
		usuario: req.params.usuario,
		clave: req.params.clave,
		proveedor: req.params.proveedor,
		apellido: req.params.apellido,
		nombre: req.params.nombre,
		email: JSON.stringify(req.params.email),
		foto: JSON.stringify(req.params.foto)
	};
}

export function clarificaUser(user) {
	var ret = {
		id: user.usuario,
		usuario: user.usuario,
		proveedor: user.proveedor,
		apellido: user.apellido,
		nombre: user.nombre,
	};
	try {
		ret.email = JSON.parse(user.email);
	} catch(e) { ret.email = []; }
	try {
		ret.foto = JSON.parse(user.foto);
	} catch(e) { ret.foto = []; }
 
	return ret;
}

export async function encuentraUser(usuario) {
	let user = await SQUser.findOne({ where: { usuario: usuario }});
	user = user ? clarificaUser(user) : undefined;
	return user;
}

export async function crearUser(req) {
	let creador = paramsUser(req);
	await SQUser.create(creador);
	const resultado = await encuentraUser(req.params.usuario);
	return resultado;
}
