'''
    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 os
import pytz
import flask

from ..database.Model import db, User, ApiKey, Water, OsmType, Gauge, Device, Log, Queue, ProcessingStatus, db_setup
from ..tasks.tasks import log_process

def setup():
	db_setup()
	
	print("CREATING DATABASE DEMO CONTENT...")
	with db.session.no_autoflush:
		test_user_john = None
		query = User.query.filter_by(username='john').all()
		if len(query) == 1:
			test_user_john = query[0]
		else:
			test_user_john = User.factory('john', 'testpass2', 'john@example.org')
			test_user_john.activation_code = 'dac9630aec642a428cd73f4be0a03569'
			test_user_john.license_accepted = True
			db.session.add(test_user_john)
			db.session.commit()
		
		test_user_jane = None
		query = User.query.filter_by(username='jane').all()
		if len(query) == 1:
			test_user_jane = query[0]
		else:
			test_user_jane = User.factory('jane', 'testpass', 'jane@example.org')
			test_user_jane.activated = True
			test_user_jane.first_name = 'Jane'
			test_user_jane.license_accepted = True
			db.session.add(test_user_jane)
			db.session.commit()
			
		if len(ApiKey.query.filter_by(key='DelApiKey4711').all()) < 1:
			db.session.add(ApiKey(user=test_user_jane, key='DelApiKey4711'))
			db.session.commit()
		if len(ApiKey.query.filter_by(key='test_key_jane').all()) < 1:
			db.session.add(ApiKey(user=test_user_jane, key='test_key_jane'))
			db.session.commit()
		
		mississippi = None
		query = Water.query.filter_by(name='Mississippi').all()
		if len(query) == 1:
			mississippi = query[0]
		else:
			mississippi = Water(name='Mississippi', manager=test_user_jane, osm_id=1756854, osm_type=OsmType.Relation)
			db.session.add(mississippi)
			db.session.commit()
		
		if len(Water.query.filter_by(name='Forggensee').all()) < 1:
			forggensee = Water(name='Forggensee', manager=test_user_john, osm_id=897899, osm_type=OsmType.Relation)
			db.session.add(forggensee)
			db.session.commit()
		
		pfuhlersee = None
		query = Water.query.filter_by(name='Pfuhler See').all()
		if len(query) == 1:
			pfuhlersee = query[0]
		else:
			pfuhlersee = Water(name='Pfuhler See', manager=test_user_jane, osm_id=225888565, osm_type=OsmType.Way)
			db.session.add(pfuhlersee)
			db.session.commit()
		
		new_orleans = None
		query = Gauge.query.filter_by(name='New Orleans').all()
		if len(query) == 1:
			new_orleans = query[0]
		else:
			new_orleans = Gauge(name='New Orleans', manager=test_user_jane, water=mississippi, location='SRID=4326;POINT(-90.136111 29.934722)', reference_water_level_gauge_height=3)
			db.session.add(new_orleans)
			db.session.commit()
			
		pfuhlersee_gauge = None
		query = Gauge.query.filter_by(name='Stairs at Kiosk').all()
		if len(query) == 1:
			pfuhlersee_gauge = query[0]
		else:
			pfuhlersee_gauge = Gauge(name='Stairs at Kiosk', manager=test_user_jane, water=pfuhlersee, location='SRID=4326;POINT(10.0427 48.4275)', reference_water_level_gauge_height=0.4, comment='Level zero is the level of the step where the handrail is fixed.')
			db.session.add(pfuhlersee_gauge)
			db.session.commit()
		
		gnuboat_one = None
		query = Device.query.filter_by(name='GnuBoat 1').all()
		if len(query) == 1:
			gnuboat_one = query[0]
		else:
			gnuboat_one = Device(name='GnuBoat 1', owner=test_user_jane, sensor_depth=0.2, comment='SUP attachment')
			db.session.add(gnuboat_one)
			db.session.commit()
		
		log_file = 'sample-logs/nmea0183-2017-12-09.log'
		sample_log = os.path.join('/usr/share/doc/gnuboat', log_file)
		if os.path.isfile(sample_log):
			_sample_log_add(pfuhlersee, pfuhlersee_gauge, 0, gnuboat_one, test_user_jane, sample_log)
		else:
			sample_log = os.path.join(os.path.dirname(__file__), '../../../../../../', log_file)
			if os.path.isfile(sample_log):
				_sample_log_add(pfuhlersee, pfuhlersee_gauge, 0, gnuboat_one, test_user_jane, sample_log)
			else:
				print('Demo log not found --> Skipping')
		
		print("...Finished")

def _sample_log_add(water, gauge, gauge_height, device, submitter, log_file):
	if len(Log.query.filter_by(submitter=submitter).all()) > 0:
		return None
	
	log = Log(submitter=submitter, water=water, device=device, gauge=gauge, gauge_height=0, comment='Demo Log from {}'.format(log_file))
	db.session.add(log)
	db.session.commit()
	
	if not 'CELERY_BROKER_URL' in flask.current_app.config or not flask.current_app.config['CELERY_BROKER_URL']:
		print('Do not add log, since their is no CELERY_BROKER_URL configured')
		return log
	
	with open(log_file, 'r') as logfile:
		data = logfile.read()
  
	processing_state = ProcessingStatus.query.filter_by(label='Queued for Parsing').all()
	if len(processing_state) != 1:
		raise MapserviceBadRequest(detail='Processing status Queued for Parsing not found database')
	processing_state = processing_state[0]
	
	# Add Log to Queued table and change the processing state of Log
	queue = Queue(log=log)
	db.session.add(queue)
	log.processingstatus = processing_state
	db.session.commit()
	
	# request log parsing
	log_process.delay(log.id, data)
	return log
