# -*- 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/>.
#
################################################################################
"""
View for farmOS animal types
"""

import datetime

import colander

from wuttaweb.forms.schema import WuttaDateTime

from wuttafarm.web.views.farmos import FarmOSMasterView


class AnimalTypeView(FarmOSMasterView):
    """
    Master view for Animal Types in farmOS.
    """

    model_name = "farmos_animal_type"
    model_title = "farmOS Animal Type"
    model_title_plural = "farmOS Animal Types"

    route_prefix = "farmos_animal_types"
    url_prefix = "/farmOS/animal-types"

    farmos_refurl_path = "/admin/structure/taxonomy/manage/animal_type/overview"

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

    sort_defaults = "name"

    form_fields = [
        "name",
        "description",
        "changed",
    ]

    def get_grid_data(self, columns=None, session=None):
        animal_types = self.farmos_client.resource.get("taxonomy_term", "animal_type")
        return [self.normalize_animal_type(t) for t in animal_types["data"]]

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

        # name
        g.set_link("name")
        g.set_searchable("name")

        # changed
        g.set_renderer("changed", "datetime")

    def get_instance(self):
        animal_type = self.farmos_client.resource.get_id(
            "taxonomy_term", "animal_type", self.request.matchdict["uuid"]
        )
        self.raw_json = animal_type
        return self.normalize_animal_type(animal_type["data"])

    def get_instance_title(self, animal_type):
        return animal_type["name"]

    def normalize_animal_type(self, animal_type):

        if changed := animal_type["attributes"]["changed"]:
            changed = datetime.datetime.fromisoformat(changed)
            changed = self.app.localtime(changed)

        if description := animal_type["attributes"]["description"]:
            description = description["value"]

        return {
            "uuid": animal_type["id"],
            "drupal_id": animal_type["attributes"]["drupal_internal__tid"],
            "name": animal_type["attributes"]["name"],
            "description": description or colander.null,
            "changed": changed,
        }

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

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

        # changed
        f.set_node("changed", WuttaDateTime())

    def get_xref_buttons(self, animal_type):
        model = self.app.model
        session = self.Session()

        buttons = [
            self.make_button(
                "View in farmOS",
                primary=True,
                url=self.app.get_farmos_url(
                    f"/taxonomy/term/{animal_type['drupal_id']}"
                ),
                target="_blank",
                icon_left="external-link-alt",
            )
        ]

        if wf_animal_type := (
            session.query(model.AnimalType)
            .filter(model.AnimalType.farmos_uuid == animal_type["uuid"])
            .first()
        ):
            buttons.append(
                self.make_button(
                    f"View {self.app.get_title()} record",
                    primary=True,
                    url=self.request.route_url(
                        "animal_types.view", uuid=wf_animal_type.uuid
                    ),
                    icon_left="eye",
                )
            )

        return buttons


def defaults(config, **kwargs):
    base = globals()

    AnimalTypeView = kwargs.get("AnimalTypeView", base["AnimalTypeView"])
    AnimalTypeView.defaults(config)


def includeme(config):
    defaults(config)
