'''
    Copyright (C) 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/>.
'''
from celery import Celery
import flask
from sqlalchemy import event

from . import config_object, app, application, celery, setup_app
from .database.Model import db
from .tasks import tasks


# see https://flask.palletsprojects.com/en/1.1.x/patterns/celery/
def setup_celery(flask_app, celery_app):
    celery_app.conf.update(flask_app.config)
    TaskBase = celery_app.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with flask_app.app_context():

                @event.listens_for(db.engine, "connect")
                def load_spatialite(dbapi_conn, connection_record):
                    if 'sqlite' in flask.current_app.config[
                        'SQLALCHEMY_DATABASE_URI']:
                        # From https://geoalchemy-2.readthedocs.io/en/latest/spatialite_tutorial.html
                        dbapi_conn.enable_load_extension(True)
                        dbapi_conn.load_extension(
                            '/usr/local/lib64/mod_spatialite'
                        )

                return TaskBase.__call__(self, *args, **kwargs)

    celery_app.Task = ContextTask

    with flask_app.app_context():
        if not 'TILES_LITTLE_ZOOM_SCHEDULE' in flask.current_app.config:
            flask.current_app.logger.error(
                'TILES_LITTLE_ZOOM_SCHEDULE not configured'
            )
            raise ImportError('TILES_LITTLE_ZOOM_SCHEDULE not configured')
        tiles_little_zoom_schedule = flask.current_app.config[
            'TILES_LITTLE_ZOOM_SCHEDULE']

        celery_app.conf.beat_schedule = {
            'add-log_little_zoom_slice': {
                'task':
                    'gnuboat_mapservice.server_impl.tasks.tasks.log_little_zoom_slice',
                'schedule':
                    tiles_little_zoom_schedule
            },
        }

    return celery_app


setup_app('GNUBoat Celery Worker', config_object)
setup_celery(application, celery)
