"""
_____________________________________________________________________.

:PROJECT: LARAsuite

*lara_django_base app *

:details: lara_django_base app configuration. 
         This provides a generic django app configuration mechanism.
         For more details see:
         https://docs.djangoproject.com/en/4.0/ref/applications/
         - 
:authors: mark doerr <mark.doerr@uni-greifswald.de>
________________________________________________________________________
"""

import os

from django.apps import AppConfig
from django.conf import settings
from django.urls import include, path

from .object_factory import ObjectFactory


class SyncService(ObjectFactory):
    """SyncService is a factory for SyncBuilderInterface"""

    def get(self, service_id, **kwargs):
        return self.create(service_id.strip().lower(), **kwargs)

from SPARQLWrapper import SPARQLWrapper, JSON, RDF, CSV, TURTLE, DIGEST

from emmopy import get_emmo
from ontopy import World
from rdflib import *


class LaraDjangoBaseConfig(AppConfig):
    name = "lara_django_base"
    url_path = ''
    default_auto_field = "django.db.models.BigAutoField"
    # enter a verbose name for your app: lara_django_base here - this will be used in the admin interface
    verbose_name = "LARA-django Base"
    # lara_app_icon = 'lara_django_base_icon.svg'  # this will be used to display an icon, e.g. in the main LARA menu.
    lara_app_icon = "LARA_logo.svg"

    # sparql = SPARQLWrapper(f'http://{settings.VIRTUOSO_HOST}:{settings.VIRTUOSO_ADMIN_PORT}/sparql-auth/')
    # sparql.setHTTPAuth(DIGEST)
    # sparql.setCredentials(settings.VIRTUOSO_USER, settings.VIRTUOSO_PASSWORD)
    # sparql.setReturnFormat(JSON)
    # def __init__(self, app_name, app_module):
    #     super().__init__(app_name, app_module)

    def ready(self):

        # add urlpatterns 
        from lara_django.urls import urlpatterns

        urlpatterns += [ 
            path(self.url_path, include('lara_django_base.urls', namespace='lara_django_base')),
        ]

        # adding WEBPACK_LOADER

        app_static_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static", "webpack_bundles")
        stats_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static", "webpack-stats-base-dev.json")
        settings.WEBPACK_LOADER['BASE'] = {
            "CACHE": not settings.DEBUG,
            "BUNDLE_DIR_NAME": app_static_dir + "/",
            "STATS_FILE": stats_file,
            "POLL_INTERVAL": 0.9,
            "IGNORE": [r".+\.hot-update.js", r".+\.map"],
            "LOADER_CLASS": "webpack_loader.loader.WebpackLoader",
        }

        self.sparql = SPARQLWrapper(f"http://{settings.VIRTUOSO_HOST}:{settings.VIRTUOSO_ADMIN_PORT}/sparql-auth/")
        self.sparql.setHTTPAuth(DIGEST)
        self.sparql.setCredentials(settings.VIRTUOSO_USER, settings.VIRTUOSO_PASSWORD)
        self.sparql.setReturnFormat(JSON)

        # loading the EMMO ontology

        if settings.ONTOLOGY_PATH:
            oso_data_url = os.path.join(settings.ONTOLOGY_PATH, "lara_django_data_corr.ttl") # "oso_data.ttl")
        else:
            # oso_data_filename = "../ontologies/oso_data.ttl"
            oso_data_url = "https://gitlab.com/opensourcelab/scientificdata/ontologies/openscienceontology/data/-/raw/main/ontologies/oso_data.ttl"

        self.lara_onto_world = World()
        self.lara_onto = self.lara_onto_world.get_ontology(oso_data_url)
        self.lara_onto.load()  # reload_if_newer = True
        self.lara_onto.sync_python_names()  # synchronize annotations

        print(f"LARA ontologies loaded ... : {oso_data_url}" )

        self.lara_onto_graph = self.lara_onto_world.as_rdflib_graph()
        lara_onto_iri = "http://lara_onto.info/lara_onto-inferred#"
        abox_iri = "http://w3id.org/lara/lara_abox#"
        tbox_iri = "http://w3id.org/lara/lara__tbox#"
        self.lara_onto_graph.bind("lara_onto", lara_onto_iri)
        self.lara_onto_graph.bind("tbox", tbox_iri)
        self.lara_onto_graph.bind("abox", abox_iri)
        self.lara_onto_graph.bind("owl", "http://www.w3.org/2002/07/owl#")

        self.sync_service = SyncService()

        LARA_welcome_txt = (
            "_____________________________________________\n\n"
            "  Welcome to                                 \n"
            "   __      __    ____    __                  \n"
            "  (  )    /__\  (  _ \  /__\                 \n"
            "   )(__  /(__)\  )   / /(__)\                \n"
            "  (____)(__)(__)(_)\_)(__)(__)               \n"
            "                                             \n"
            "   To access LARA go to:                     \n"
            f"     https://{settings.LARA_HOSTNAME}:{settings.LARA_PORT}\n"
            "        \n"
            "_____________________________________________\n\n"
        )

        print(LARA_welcome_txt)
