# -*- 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


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

    farmos_refurl_path = 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 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):
        super().persist(obj, session)
        self.app.export_to_farmos(obj, require=False)
