# -*- coding: utf-8; -*-
################################################################################
#
#  WuttaFarm --Web app to integrate with and extend farmOS
#  Copyright © 2026 Lance Edgar
#
#  This file is part of WuttaFarm.
#
#  WuttaFarm 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.
#
#  WuttaFarm 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
#  WuttaFarm.  If not, see <http://www.gnu.org/licenses/>.
#
################################################################################
"""
Custom app handler for WuttaFarm
"""

from wuttjamaican import app as base


class WuttaFarmAppHandler(base.AppHandler):
    """
    Custom :term:`app handler` for WuttaFarm.
    """

    display_format_datetime = "%a, %m/%d/%Y - %H:%M"

    default_auth_handler_spec = "wuttafarm.auth:WuttaFarmAuthHandler"
    default_install_handler_spec = "wuttafarm.install:WuttaFarmInstallHandler"

    def get_farmos_handler(self):
        """
        Get the configured farmOS integration handler.

        :rtype: :class:`~wuttafarm.farmos.FarmOSHandler`
        """
        if "farmos" not in self.handlers:
            spec = self.config.get(
                f"{self.appname}.farmos_handler",
                default="wuttafarm.farmos.handler:FarmOSHandler",
            )
            factory = self.load_object(spec)
            self.handlers["farmos"] = factory(self.config)
        return self.handlers["farmos"]

    def get_farmos_url(self, *args, **kwargs):
        """
        Get a farmOS URL.  This is a convenience wrapper around
        :meth:`~wuttafarm.farmos.handler.FarmOSHandler.get_farmos_url()`.
        """
        handler = self.get_farmos_handler()
        return handler.get_farmos_url(*args, **kwargs)

    def get_farmos_client(self, *args, **kwargs):
        """
        Get a farmOS client.  This is a convenience wrapper around
        :meth:`~wuttafarm.farmos.handler.FarmOSHandler.get_farmos_client()`.
        """
        handler = self.get_farmos_handler()
        return handler.get_farmos_client(*args, **kwargs)

    def is_farmos_3x(self, *args, **kwargs):
        """
        Check if the farmOS version is 3.x.  This is a convenience
        wrapper around
        :meth:`~wuttafarm.farmos.handler.FarmOSHandler.is_farmos_3x()`.
        """
        handler = self.get_farmos_handler()
        return handler.is_farmos_3x(*args, **kwargs)

    def is_farmos_4x(self, *args, **kwargs):
        """
        Check if the farmOS version is 4.x.  This is a convenience
        wrapper around
        :meth:`~wuttafarm.farmos.handler.FarmOSHandler.is_farmos_4x()`.
        """
        handler = self.get_farmos_handler()
        return handler.is_farmos_4x(*args, **kwargs)

    def export_to_farmos(self, obj, require=True):
        """
        Export the given object to farmOS, using configured handler.

        This should ensure the given object is also *updated* with the
        farmOS UUID and Drupal ID, when new record is created in
        farmOS.

        :param obj: Any data object in WuttaFarm, e.g. AnimalAsset
           instance.

        :param require: If true, this will *require* the export
           handler to support objects of the given type.  If false,
           then nothing will happen / export is silently skipped when
           there is no such exporter.
        """
        handler = self.app.get_import_handler("export.to_farmos.from_wuttafarm")

        model_name = type(obj).__name__
        if model_name not in handler.importers:
            if require:
                raise ValueError(f"no exporter found for {model_name}")
            return

        # nb. begin txn to establish the API client
        # TODO: should probably use current user oauth2 token instead
        # of always making a new one here, which is what happens IIUC
        handler.begin_target_transaction()
        importer = handler.get_importer(model_name, caches_target=False)
        normal = importer.normalize_source_object(obj)
        importer.process_data(source_data=[normal])


class WuttaFarmAppProvider(base.AppProvider):
    """
    The :term:`app provider` for WuttaFarm.
    """

    email_modules = ["wuttafarm.emails"]
