"""Set settings of application object"""
import os
from pathlib import Path

from defence360agent import files
from defence360agent.application import tags
from defence360agent.contracts import eula
from defence360agent.internals.global_scope import g
from defence360agent.model import simplification
from defence360agent.rpc_tools.validate import (
    SchemaValidator,
    validate_middleware,
)
from defence360agent.simple_rpc.schema import init_validator
from defence360agent.wordpress.plugin import update_wp_rules_on_sites

from . import app


async def update_eula_data(index, is_updated: bool):
    if is_updated:
        await eula.update()


def configure(
    init_validator=init_validator,
    validator_cls=SchemaValidator,
    validate_middleware_wrap=validate_middleware,
    schema_paths=None,
    models_modules=None,
    set_sentry_tags=tags.fill,
    migration_dirs=None,
    migrations_attached_dbs=None,
    resident=False,
):
    if os.environ.get("DEBUG") == "true":
        g.DEBUG = True
    app.SCHEMA_PATHS = schema_paths
    app.VALIDATOR, app.MIDDLEWARE, app.MIDDLEWARE_EXCLUDE = init_validator(
        validator_cls, validate_middleware_wrap, schema_paths
    )
    app.MODULES_WITH_MODELS += [simplification]
    if models_modules:
        app.MODULES_WITH_MODELS += models_modules
    av_path = Path(__file__).resolve().parent.parent
    app.MIGRATIONS_DIRS += [av_path / "migrations"]
    if migration_dirs:
        app.MIGRATIONS_DIRS += migration_dirs
    if migrations_attached_dbs:
        app.MIGRATIONS_ATTACHED_DBS += migrations_attached_dbs

    set_sentry_tags()
    files.configure()
    if not resident:
        files.Index.add_hook(files.EULA, update_eula_data)
        files.Index.add_hook(files.WP_RULES, update_wp_rules_on_sites)
