'''
    Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''
import connexion

import datetime
import hashlib
import re
import flask
from flask import request, render_template
from flask_mail import Message

from .. import mail
from ..database.Model import User, ApiKey, db
from ..HttpErrors import MapserviceBadRequest, MapserviceUnauthorized, MapserviceNotFound

mail_regex = re.compile('[^@]+@[^@]+\.[^@]+')

def users_activate(activationCode):
	user = User.query.filter_by(activation_code=activationCode).all()
	
	webclient = flask.current_app.config['MAPSERVICE_WEBCLIENT']
	
	if len(user) != 1:
		return 'Bad Request', 302, {'Location': 'activation_failed.html'}
	
	user = user[0]
	user.activated = True
	user.activation_code = ""
	db.session.commit()
	return 'Success', 302, {'Location': '{}/login'.format(webclient)}

def users_api_key_create():
	user = User.loggedin_user()
	if user is None:
		raise MapserviceUnauthorized
	
	api_key = hashlib.md5("{}{}".format(datetime.datetime.now().strftime("%Y%m%d%H%M%S"), user.salt).encode()).hexdigest()
	user.apikeys.append(ApiKey(user=user, key=api_key))
	db.session.commit()

	result = []
	for apiKey in user.apikeys:
		result.append(apiKey.key)
	return result

def users_api_key_delete(api_key):
	user = User.loggedin_user()
	if user is None:
		raise MapserviceUnauthorized
	
	if not ApiKey.query.filter_by(key=api_key).delete():
		raise MapserviceBadRequest(detail="Could not delete api key {}".format(api_key))
	db.session.commit()
	
	result = []
	for apiKey in user.apikeys:
		result.append(apiKey.key)
	return result

def users_get():
	user = User.loggedin_user()
	if user is None:
		raise MapserviceUnauthorized
	
	return user_to_dict(user)

def users_register(user_creation):
	if user_creation is None:
		raise MapserviceBadRequest(detail='No data specified')
	if user_creation.username is None or not user_creation.username:
		raise MapserviceBadRequest(detail='No username given')
	if user_creation.password is None or not user_creation.password:
		raise MapserviceBadRequest(detail='No password given')
	if user_creation.first_name is None or not user_creation.first_name:
		raise MapserviceBadRequest(detail='No first name given')
	if user_creation.last_name is None or not user_creation.last_name:
		raise MapserviceBadRequest(detail='No last name given')
	if user_creation.email is None or not user_creation.email:
		raise MapserviceBadRequest(detail='No email given')
	if not mail_regex.match(user_creation.email):
		raise MapserviceBadRequest(detail='Email contains more than one @, no @ or no .')
	if user_creation.license_accepted is None or not user_creation.license_accepted:
		raise MapserviceBadRequest(detail='You must accept the license to register an account')
	
	# add user to the database
	user = User.factory(user_creation.username, user_creation.password, user_creation.email)
	user.first_name = user_creation.first_name
	user.last_name = user_creation.last_name
	user.license_accepted = user_creation.license_accepted
	db.session.add(user)
	db.session.commit()
	
	# send activation mail
	activation_url = '{}/activate/{}'.format(request.base_url, user.activation_code)
	
	message = Message("Activate your GNUBoat account", recipients=[user.email])
	message.body = 'Hello {},\nthank you for support the project with your own measurings. To activate your GNUBoat account, visit {}.\nKind regards,\nYour GNUBoat team'.format(user.first_name, activation_url)
	message.html = render_template('activation_mail.html', first_name=user.first_name, activation_url=activation_url)
	mail.send(message)
	
	return user_to_dict(user)

def user_to_dict(user):
	# create user dict and remove not needed entries
	result = user.to_dict()
	del result['password']
	del result['salt']
	del result['activationCode']
	
	# add api keys of the user to the result dict
	result['apiKeys'] = []
	for apiKey in user.apikeys:
		result['apiKeys'].append(apiKey.key)
	return result
