'''
    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 flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import inspect, text, Enum, event, select, func
from sqlalchemy.orm.attributes import get_history
from geoalchemy2 import Geometry
from geoalchemy2.shape import to_shape
from sqlalchemy_utc import UtcDateTime
from sqlalchemy_utils import create_view, database_exists, create_database
import hashlib
import datetime
import enum
import connexion
from pathlib import Path
import sys
import os

db = SQLAlchemy()

class OsmType(enum.Enum):
	Node = 1
	Way = 2
	Relation = 3

def wkb_to_dict(wkbelement):
	point = to_shape(wkbelement)
	return {'longitude': point.x, 'latitude': point.y}

class User(db.Model):
	__tablename__ = "users"
	
	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
	username = db.Column(db.String(255), nullable=False, unique=True)
	password = db.Column(db.String(50), nullable=False)
	salt = db.Column(db.String(50), nullable=False)
	email = db.Column(db.String(255), nullable=False)
	first_name = db.Column(db.String(255))
	last_name = db.Column(db.String(255))
	activated = db.Column(db.Boolean(), default=False)
	activation_code = db.Column(db.String(255), default='1234')
	#activation_code = db.Column(db.String(255), server_default=text('LEFT(MD5(NOW()), 50)'))
	license_accepted = db.Column(db.Boolean(), default=False)
	
	def to_dict(user):
		result = {
			'username': user.username,
			'password': user.password,
			'salt': user.salt,
			'email': user.email,
			'firstName': "",
			'lastName': "",
			'activated': user.activated,
			'licenseAccepted': user.license_accepted
		}
		if user.first_name is not None:
			result['firstName'] = user.first_name
		if user.last_name is not None:
			result['lastName'] = user.last_name
		if user.activation_code is not None:
			result['activationCode'] = user.activation_code
		
		return result
	
	def factory(username, password, email):
		salt = hashlib.md5('{}{}'.format(username, datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')).encode()).hexdigest()
		password = hashlib.md5('{}{}'.format(password, salt).encode()).hexdigest()
		activation_code = hashlib.md5('{}'.format(datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')).encode()).hexdigest()
		return User(username=username, password=password, email=email, salt=salt, activated=False, activation_code=activation_code)
	
	def password_verify(self, password):
		return hashlib.md5("{}{}".format(password, self.salt).encode()).hexdigest() == self.password
	
	@staticmethod
	def loggedin_username():
		if not 'user' in connexion.context:
			return None
		return connexion.context['user']

	@staticmethod
	def loggedin_user():
		username = User.loggedin_username()
		if username is None:
			return None
		user = User.query.filter_by(username=username).all()
		if len(user) != 1:
			return None
		return user[0]

class ApiKey(db.Model):
	__tablename__ = "apikeys"

	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
	user_id = db.Column(db.BigInteger, db.ForeignKey('users.id'))
	key = db.Column(db.String(255), nullable=False, unique=True)
	user = db.relationship("User", backref=db.backref("apikeys"), lazy=True)
	
class Water(db.Model):
	__tablename__ = "waters"
	
	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
	name = db.Column(db.String(255), nullable=False)
	manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))
	osm_id = db.Column(db.Integer)
	osm_type = db.Column(Enum(OsmType))
	manager = db.relationship("User", backref=db.backref("waters"), lazy=True)
	
	def to_dict(obj):
		result = { 'waterId': obj.id, 'name': obj.name }
		if obj.manager:
			result['manager'] = obj.manager.username
		if obj.osm_id:
			result['osmId'] = obj.osm_id
		if obj.osm_type:
			result['osmType'] = obj.osm_type.name
		if obj.gauges:
			result['gauges'] = []
			for gauge in obj.gauges:
				result['gauges'].append(gauge.to_dict())
		if obj.logs:
			logs = []
			for log in obj.logs:
				logs.append(log.meta_data())
			result['logs'] = logs
		return result
	
class Gauge(db.Model):
	__tablename__ = "gauges"
	
	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
	name = db.Column(db.String(255), nullable=False)
	manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))
	water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
	# POINT(Lon Lat)
	location = db.Column(Geometry(geometry_type='POINT', srid=4326, management=True))
	reference_water_level_gauge_height = db.Column(db.Float, nullable = False)
	comment = db.Column(db.String(255))
	#osm_id = db.Column(db.Integer)
	#osm_type = db.Column(db.String(255))
	#osm_class = db.Column(db.String(255))
	manager = db.relationship("User", backref=db.backref("gauges"), lazy=True)
	water = db.relationship("Water", backref=db.backref("gauges"), lazy=True)
	
	def to_dict(obj):
		result = { 'gaugeId': obj.id, 'name': obj.name }
		if obj.manager:
			result['manager'] = obj.manager.username
		location = wkb_to_dict(obj.location)
		result['location'] = [location['longitude'], location['latitude']]
		result['referenceWaterLevelGaugeHeight'] = obj.reference_water_level_gauge_height
		if obj.water:
			result['water'] = { 'label': obj.water.name, 'id': obj.water.id }
		if obj.logs:
			logs = []
			for log in obj.logs:
				logs.append(log.meta_data())
			result['logs'] = logs
		if obj.comment:
			result['comment'] = obj.comment
		return result
	
	def to_geojson(obj):
		location = wkb_to_dict(obj.location)
		result = {
			'type': 'Feature',
			'geometry': {
				'type': 'Point',
				'coordinates': [location['longitude'], location['latitude']]
			},
			'properties': {
				'name': obj.name,
				'referenceWaterLevelGaugeHeight': obj.reference_water_level_gauge_height
			}
		}
		if obj.manager:
			result['properties']['manager'] = obj.manager.username
		if obj.comment:
			result['properties']['comment'] = obj.comment
		return result
	
class Device(db.Model):
	__tablename__ = "devices"
	
	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
	name = db.Column(db.String(255), nullable=False)
	owner_id = db.Column(db.Integer, db.ForeignKey('users.id'))
	sensor_depth = db.Column(db.Float, nullable=False)
	comment = db.Column(db.String(255))
	
	owner = db.relationship("User", backref=db.backref("devices"), lazy=True)
	
	def to_dict(obj):
		result = { 'deviceId': obj.id, 'name': obj.name, 'sensorDepth': obj.sensor_depth }
		if obj.logs:
			logs = []
			for log in obj.logs:
				logs.append(log.meta_data())
			result['logs'] = logs
		if obj.comment:
			result['comment'] = obj.comment
		return result

class ProcessingStatus(db.Model):
	__tablename__ = "processingstatus"
	
	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
	label = db.Column(db.String(255), nullable=False)
	
	@staticmethod
	def insert_states():
		states = [ 'Undefined', 'Queued for Parsing', 'Parsing', 'Queued for Processing', 'Processing', 'Deployed', 'To Old', 'Error' ]
		changed = False
		for state in states:
			query = ProcessingStatus.query.filter_by(label=state).all()
			if len(query) != 1:
				state = ProcessingStatus(label=state)
				db.session.add(state)
				changed = True
		if changed:
			db.session.commit()

class Log(db.Model):
	__tablename__ = "logs"
	
	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
	submitter_id = db.Column(db.Integer, db.ForeignKey('users.id'))
	water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
	device_id = db.Column(db.Integer, db.ForeignKey('devices.id'))
	gauge_id = db.Column(db.Integer, db.ForeignKey('gauges.id'))
	gauge_height = db.Column(db.Float, nullable=False)
	start = db.Column(UtcDateTime, nullable=True)
	end = db.Column(UtcDateTime, nullable=True)
	processing_state = db.Column(db.Integer, db.ForeignKey('processingstatus.id'), default=1)
	comment = db.Column(db.String(255))
	
	submitter = db.relationship("User", backref=db.backref("logs"), lazy=True)
	water = db.relationship("Water", backref=db.backref("logs"), lazy=True)
	device = db.relationship("Device", backref=db.backref("logs"), lazy=True)
	gauge = db.relationship("Gauge", backref=db.backref("logs"), lazy=True)
	processingstatus = db.relationship("ProcessingStatus", backref=db.backref("logs"), lazy=True)
	
	def meta_data(obj):
		result = {
			'logId': obj.id,
			'submitter': obj.submitter.username,
			'water': {
				'id': obj.water.id,
				'label': obj.water.name,
			},
			'device': {
				'id': obj.device.id,
				'label': obj.device.name,
			},
			'gauge': {
				'id': obj.gauge.id,
				'label': obj.gauge.name,
			},
			'gaugeHeight': obj.gauge_height,
			'start': '',
			'end': '',
			'processingState': {
				'id': obj.processingstatus.id,
				'label': obj.processingstatus.label
			}
		}
		if obj.start is not None:
			result['start'] = obj.start.isoformat('T')
		if obj.end is not None:
			result['end'] = obj.end.isoformat('T')
			
		entries_count = 0
		if obj.log_entries:
			entries_count = len(obj.log_entries)
		result['entriesCount'] = entries_count
		if obj.comment:
			result['comment'] = obj.comment
		return result
	
	def log(obj):
		result = { 'metaData': obj.meta_data() }
		entries = []
		if obj.log_entries:
			for log in obj.log_entries:
				entries.append(log.to_dict())
		result['entries'] = entries
		return result
	
	def to_geojson(obj):
		result = {
			'type': 'FeatureCollection',
			'features': []
		}
		if obj.log_entries:
			for log in obj.log_entries:
				location = wkb_to_dict(log.location)
				feature = {
					'type': 'Feature',
					'geometry': {
						'type': 'Point',
						'coordinates': [location['longitude'], location['latitude']]
					},
					'properties': {
						'datetime': log.datetime.isoformat('T')
					}
				}
				if log.water_depth is not None:
					feature['properties']['waterDepth'] = log.water_depth
				result['features'].append(feature)
		return result

class LogEntry(db.Model):
	__tablename__ = "logentries"
	
	id = db.Column(db.Integer, primary_key=True, autoincrement=True)
	log_id = db.Column(db.Integer, db.ForeignKey('logs.id'))
	datetime = db.Column(UtcDateTime, nullable=False)
	# POINT(Lon Lat)
	location = db.Column(Geometry(geometry_type='POINT', srid=4326, management=True))
	water_depth = db.Column(db.Float)
	
	log = db.relationship("Log", backref=db.backref("log_entries"), lazy=True)
	
	def to_dict(obj):
		result = {'datetime': obj.datetime.isoformat('T') }
		location = wkb_to_dict(obj.location)
		result['location'] = [location['longitude'], location['latitude']]
		if obj.water_depth:
			result['waterDepth'] = obj.water_depth
		return result

class LogView(db.Model):
	__table__ = create_view(
		name='logview',
		metadata=db.Model.metadata,
		selectable=select(
			[
				Log.id,
				Log.submitter_id,
				Log.water_id,
				Log.device_id,
				Log.gauge_id,
				Log.gauge_height,
				Log.start,
				Log.end,
				ProcessingStatus.label,
				func.Envelope(func.MakeLine(LogEntry.location)).label('envelope')
			],
			from_obj=(Log.__table__.join(LogEntry, Log.id == LogEntry.log_id).join(ProcessingStatus, Log.processing_state == ProcessingStatus.id)),
			group_by=(Log.id)
		),
		cascade_on_drop=False
	)

class Queue(db.Model):
	__tablename__ = "queue"
	
	log_id = db.Column(db.Integer, db.ForeignKey('logs.id'), primary_key=True)
	datetime = db.Column(UtcDateTime, nullable=False, default=datetime.datetime.now(datetime.timezone.utc))

	log = db.relationship("Log", backref=db.backref("queue"), lazy=True)

def db_setup(force = False):
	if not database_exists(db.engine.url) or force:
		create_database(db.engine.url)
		if 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
			result = db.engine.execute('SELECT count(name) FROM sqlite_master WHERE type="table" AND name="spatial_ref_sys"')
			if result.fetchone()[0] == 1:
				print('Spatial lite extension already loaded')
			else:
				print("Initiate spatial meta data for Spatialite...")
				db.engine.execute(select([func.InitSpatialMetaData()]))
				print("...Finished")
		db.create_all()
		ProcessingStatus.insert_states()
		
def load_spatialite(dbapi_conn, connection_record):
	if not 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
		return
	
	paths = [os.path.join(sys.prefix, 'lib'), os.path.join(sys.prefix, 'lib64'), '/usr/lib', '/usr/lib64']
	for path in paths:
		if _load_spatialite_from_path(path, dbapi_conn, connection_record):
			return True
	raise FileNotFoundError('mod_spatialite not found in folders {}'.format(', '.join(paths)))
			
def _load_spatialite_from_path(search_path, dbapi_conn, connection_record):
	for path in Path(search_path).rglob('mod_spatialite.so*'):
		if os.path.exists(path):
			if flask.current_app.config['DEBUG'] and (not 'TESTING' in flask.current_app.config or not flask.current_app.config['TESTING']):
				print('Enabling spatial lite extension. This may take a while')
			# From https://geoalchemy-2.readthedocs.io/en/latest/spatialite_tutorial.html
			dbapi_conn.enable_load_extension(True)
			dbapi_conn.load_extension(str(path.resolve()))
			return True
	return False
