'''
    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 flask
from flask_cors import CORS
from flask_mail import Mail
from sqlalchemy import event
from celery import Celery
from werkzeug.utils import import_string
import os

from .. import encoder
from .database.Model import db, User, ApiKey, db_setup, load_spatialite
from .ValidatorWorkaround import ValidatorWorkaround

def load_config_object(config_name):
	return import_string('gnuboat_mapservice.server_impl.Config.{}Config'.format(config_name))

# determine requested configuration
config_file = '/etc/gnuboat/mapservice.conf'
if 'FLASK_ENV' in os.environ and os.environ['FLASK_ENV']:
	config_object = load_config_object(os.environ['FLASK_ENV'].title())
elif os.path.isfile(config_file):
	from . import Config as configure
	config_object = configure.load_from_file(config_file)
else:
	config_object = load_config_object('Production')

app = connexion.App(__name__, specification_dir='../openapi/')
application = app.app
CORS(application)
mail = Mail()
celery = Celery(__name__, broker=config_object.CELERY_BROKER_URL)

@application.before_first_request
def create_database():
	@event.listens_for(db.engine, "connect")
	def load_spatialite_extension(dbapi_conn, connection_record):
		load_spatialite(dbapi_conn, connection_record)
			

	if flask.current_app.config['CREATE_TEST_DATABASE'] == True:
		from .demo import DbSetup as demoDbSetup
		demoDbSetup.setup()
	else:
		db_setup()

@application.route("/mapservice/")
def index():
	return render_template('index.html')

def setup_app(app_name, config):
	application.json_encoder = encoder.JSONEncoder
	app.add_api('openapi.yaml', arguments={'title': app_name}, validate_responses=True, strict_validation=True, validator_map={'response': ValidatorWorkaround})
	application.config.from_object(config)

	db.init_app(application)
	mail.init_app(application)
	celery.config_from_object(config)
