# -*- 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/>.
#
################################################################################
"""
Base class for WuttaFarm master views
"""

from webhelpers2.html import tags

from wuttaweb.views import MasterView
from wuttaweb.util import get_form_data

from wuttafarm.web.util import use_farmos_style_grid_links, get_farmos_client_for_user


class WuttaFarmMasterView(MasterView):
    """
    Base class for WuttaFarm master views
    """

    farmos_refurl_path = None
    farmos_entity_type = None
    farmos_bundle = None

    labels = {
        "farmos_uuid": "farmOS UUID",
        "drupal_id": "Drupal ID",
        "image_url": "Image URL",
        "thumbnail_url": "Thumbnail URL",
    }

    row_labels = {
        "farmos_uuid": "farmOS UUID",
        "drupal_id": "Drupal ID",
        "image_url": "Image URL",
        "thumbnail_url": "Thumbnail URL",
    }

    def __init__(self, request, context=None):
        super().__init__(request, context=context)
        self.farmos_style_grid_links = use_farmos_style_grid_links(self.config)

    def get_farmos_url(self, obj):
        return None

    def get_template_context(self, context):

        if self.listing and self.farmos_refurl_path:
            context["farmos_refurl"] = self.app.get_farmos_url(self.farmos_refurl_path)

        return context

    def render_grid_thumbnail(self, obj, field, value):
        if obj.thumbnail_url:
            return tags.image(
                obj.thumbnail_url, f"thumbnail for {self.get_model_title()}"
            )
        return None

    def get_xref_buttons(self, obj):
        url = self.get_farmos_url(obj)
        if url:
            return [
                self.make_button(
                    "View in farmOS",
                    primary=True,
                    url=url,
                    target="_blank",
                    icon_left="external-link-alt",
                )
            ]
        return []

    def configure_form(self, form):
        """ """
        f = form
        super().configure_form(f)

        # farmos_uuid
        if self.creating:
            f.remove("farmos_uuid")
        else:
            f.set_readonly("farmos_uuid")

        # drupal_id
        if self.creating:
            f.remove("drupal_id")
        else:
            f.set_readonly("drupal_id")

    def persist(self, obj, session=None):

        # save per usual
        super().persist(obj, session)

        # maybe also sync change to farmOS
        if self.app.is_farmos_mirror():
            client = get_farmos_client_for_user(self.request)
            self.auto_sync_to_farmos(client, obj)

    def auto_sync_to_farmos(self, client, obj):
        self.app.auto_sync_to_farmos(obj, client=client, require=False)

    def get_farmos_entity_type(self):
        if self.farmos_entity_type:
            return self.farmos_entity_type
        raise NotImplementedError(
            f"must define {self.__class__.__name__}.farmos_entity_type"
        )

    def get_farmos_bundle(self):
        if self.farmos_bundle:
            return self.farmos_bundle
        raise NotImplementedError(
            f"must define {self.__class__.__name__}.farmos_bundle"
        )

    def delete_instance(self, obj):

        # save farmOS UUID if we need it
        farmos_uuid = None
        if hasattr(obj, "farmos_uuid") and self.app.is_farmos_mirror():
            farmos_uuid = obj.farmos_uuid

        # delete per usual
        super().delete_instance(obj)

        # maybe delete from farmOS also
        if farmos_uuid:
            entity_type = self.get_farmos_entity_type()
            bundle = self.get_farmos_bundle()
            client = get_farmos_client_for_user(self.request)
            client.resource.delete(entity_type, bundle, farmos_uuid)


class TaxonomyMasterView(WuttaFarmMasterView):
    """
    Base class for master views serving taxonomy terms.
    """

    farmos_entity_type = "taxonomy_term"

    grid_columns = [
        "name",
        "description",
    ]

    sort_defaults = "name"

    filter_defaults = {
        "name": {"active": True, "verb": "contains"},
    }

    form_fields = [
        "name",
        "description",
        "drupal_id",
        "farmos_uuid",
    ]

    def configure_grid(self, grid):
        g = grid
        super().configure_grid(g)

        # name
        g.set_link("name")

    def configure_form(self, form):
        f = form
        super().configure_form(f)

        # description
        f.set_widget("description", "notes")

    def get_farmos_url(self, obj):
        return self.app.get_farmos_url(f"/taxonomy/term/{obj.drupal_id}")

    def get_xref_buttons(self, term):
        buttons = super().get_xref_buttons(term)

        if term.farmos_uuid:
            buttons.append(
                self.make_button(
                    "View farmOS record",
                    primary=True,
                    url=self.request.route_url(
                        f"{self.farmos_route_prefix}.view", uuid=term.farmos_uuid
                    ),
                    icon_left="eye",
                )
            )

        return buttons

    def ajax_create(self):
        """
        AJAX view to create a new taxonomy term.
        """
        model = self.app.model
        session = self.Session()
        data = get_form_data(self.request)

        name = data.get("name")
        if not name:
            return {"error": "Name is required"}

        term = self.model_class(name=name)
        session.add(term)
        session.flush()

        if self.app.is_farmos_mirror():
            client = get_farmos_client_for_user(self.request)
            self.app.auto_sync_to_farmos(term, client=client)

        return {
            "uuid": term.uuid.hex,
            "name": term.name,
            "farmos_uuid": term.farmos_uuid.hex,
            "drupal_id": term.drupal_id,
        }

    @classmethod
    def defaults(cls, config):
        """ """
        cls._defaults(config)
        cls._taxonomy_defaults(config)

    @classmethod
    def _taxonomy_defaults(cls, config):
        route_prefix = cls.get_route_prefix()
        permission_prefix = cls.get_permission_prefix()
        url_prefix = cls.get_url_prefix()

        # ajax_create
        config.add_route(f"{route_prefix}.ajax_create", f"{url_prefix}/ajax/new")
        config.add_view(
            cls,
            attr="ajax_create",
            route_name=f"{route_prefix}.ajax_create",
            permission=f"{permission_prefix}.create",
            renderer="json",
        )
