
import crypto from 'crypto';
import helper from './helper.js';

import Session from 'session';

import configs from 'configs';
var crds = configs('crds')['arango-accounts'];

const collectionName = crds.collectionName || 'accounts';

var tokensEmails = {};

export default {
	init(app) {
		console.log("Plugin arango-accounts");
		app.get(crds.authEmailPath || '/auth/email/:token', (req, res)=> {
			var answer = false;
			if(tokensEmails[req.params.token]) {
				answer = true;
				var session = new Session(req.session.session);
				session.id = tokensEmails[req.params.token];
				session.status = 5;
				req.session.session = session.export();
				delete tokensEmails[req.params.token];
			}
			setTimeout(()=> {
				if(answer) {
					res.redirect('/');
				} else {
					res.end('wrong token');
				}
			}, 1500);
		});
	},
	signIn(data, session, resolve, reject) {
		var email = data.email || null;
		var passwd = data.passwd || helper.randStr(8);
		var status = data.status || 5;
		var dateSignin = helper.coolDateTime();
		var mailer = this.getPlugin('mailer');
		if(!email) {
			reject("none email!");
		} else if(!(/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i).test(email)) {
			reject("wrong email");
		} else if(passwd.length < 6) {
			reject("short password");
		} else {
			var db = this.getPlugin('arangodb');
			var salt = helper.randStr(32);
			var _passwd = crypto.createHash('md5').update(passwd+salt).digest('hex');
			db.query({
				query: `
					FOR account IN ${collectionName}
						FILTER account.email == @email
						RETURN account
				`,
				data: {
					email
				}
			}).then((data)=> {
				if(data.length) {
					reject('Email exists');
				} else {
					db.query({
						query: `
							INSERT @account IN ${collectionName}
							RETURN NEW
						`,
						data: {
							account: {
								email,
								passwd: _passwd,
								status,
								salt,
								dateSignin
							}
						}
					}).then((data)=> {
						var account = data[0];
						var ret = {
							id: account._key,
							email: account.email,
							status: account.status,
							password: passwd
						};
						mailer.send({
							login: 'super.wews@yandex.ru',
							passwd: 'base64',
							service: 'Yandex',
							email: {
								from: 'super.wews@yandex.ru',
								to: email,
								subject: 'Service Registration',
								text: `Your password: ${passwd}`,
								html: `Your password: <b>${passwd}</b>`
							}
						}).then((data)=> {
							resolve(ret);
							console.log(data);
						}).catch((err)=> {
							console.error(err);
						});
					}).catch((err)=> {
						console.error(err);
						reject('DataBase Error');
					});
				}
			}).catch((err)=> {
				console.error(err);
				reject('DataBase Error');
			});
		}
	},
	emailLogIn(data, session, resolve, reject) {
		var email = data.email || null;
		if(!email) {
			reject(email);
		} else {
			var mailer = this.getPlugin('mailer');
			var token = helper.randStr(32, '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
			tokensEmails[token] = email;
			mailer.send({
				login: 'super.wews@yandex.ru',
				passwd: 'base64',
				service: 'Yandex',
				email: {
					from: 'super.wews@yandex.ru',
					to: email,
					subject: 'Service Login',
					text: `Open link: http://127.0.0.1:8080/auth/email/${token}`,
					html: `<a target="_blank" href="http://127.0.0.1:8080/auth/email/${token}">Open link</a>`
				}
			}).then((data)=> {
				console.log(data);
				resolve({
					email
				});
			}).catch((err)=> {
				reject('email sent error');
				console.error(err);
			});
		}
	},
	logIn(data, session, resolve, reject) {
		var email = data.email || null;
		var passwd = data.passwd || null;
		if(!email) {
			reject(email);
		} else {
			var db = this.getPlugin('arangodb');
			db.query({
				query: `
					FOR account IN ${collectionName}
						FILTER account.email == @email
						RETURN account
				`,
				data: {
					email
				}
			}).then((data)=> {
				if(!data.length) {
					setTimeout(function() {
						reject('wrong email or password');
					}, 1500);
				} else {
					var _passwd = crypto.createHash('md5').update(passwd+data[0].salt).digest('hex');
					if(data[0].passwd == _passwd) {
						session.id = data[0]._key;
						session.status = 5;
						setTimeout(function() {
							resolve({
								email
							});
						}, 1500);
					} else {
						setTimeout(function() {
							reject('wrong password or email');
						}, 1500);
					}
				}
			}).catch((err)=> {
				console.log(err);
				reject('DataBase Error.');
			});
		}
	},
	logOut(data, session, resolve, reject) {
		session.id = null;
		session.status = 8;
		resolve(true);
	},
	getSession(data, session, resolve, reject) {
		resolve(session.export());
	}
}