# -*- 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/>.
#
################################################################################
"""
Master view for Farm Animals
"""

import datetime

import colander

from wuttafarm.web.views.farmos import FarmOSMasterView
from wuttafarm.web.forms.widgets import AnimalImage


class AnimalView(FarmOSMasterView):
    """
    Master view for Farm Animals
    """

    model_name = "farmos_animal"
    model_title = "farmOS Animal"
    model_title_plural = "farmOS Animals"

    route_prefix = "farmos_animals"
    url_prefix = "/farmOS/animals"

    farmos_refurl_path = "/assets/animal"

    labels = {
        "is_castrated": "Castrated",
        "location_name": "Current Location",
        "raw_image_url": "Raw Image URL",
        "large_image_url": "Large Image URL",
        "thumbnail_image_url": "Thumbnail Image URL",
    }

    grid_columns = [
        "name",
        "birthdate",
        "sex",
        "is_castrated",
        "status",
    ]

    sort_defaults = "name"

    form_fields = [
        "name",
        "animal_type_name",
        "birthdate",
        "sex",
        "is_castrated",
        "status",
        "owners",
        "location_name",
        "notes",
        "raw_image_url",
        "large_image_url",
        "thumbnail_image_url",
        "image",
    ]

    def get_grid_data(self, columns=None, session=None):
        animals = self.farmos_client.resource.get("asset", "animal")
        return [self.normalize_animal(a) for a in animals["data"]]

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

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

        # birthdate
        g.set_renderer("birthdate", "date")

    def get_instance(self):

        animal = self.farmos_client.resource.get_id(
            "asset", "animal", self.request.matchdict["uuid"]
        )

        # instance data
        data = self.normalize_animal(animal["data"])

        if relationships := animal["data"].get("relationships"):

            # add animal type
            if animal_type := relationships.get("animal_type"):
                if animal_type["data"]:
                    animal_type = self.farmos_client.resource.get_id(
                        "taxonomy_term", "animal_type", animal_type["data"]["id"]
                    )
                    data["animal_type_name"] = animal_type["data"]["attributes"]["name"]

            # add location
            if location := relationships.get("location"):
                if location["data"]:
                    location = self.farmos_client.resource.get_id(
                        "asset", "structure", location["data"][0]["id"]
                    )
                    data["location_name"] = location["data"]["attributes"]["name"]

            # add owners
            if owner := relationships.get("owner"):
                owners = []
                for owner_data in owner["data"]:
                    owners.append(
                        self.farmos_client.resource.get_id(
                            "user", "user", owner_data["id"]
                        )
                    )
                data["owners"] = ", ".join(
                    [o["data"]["attributes"]["display_name"] for o in owners]
                )

            # add image urls
            if image := relationships.get("image"):
                if image["data"]:
                    image = self.farmos_client.resource.get_id(
                        "file", "file", image["data"][0]["id"]
                    )
                    data["raw_image_url"] = self.app.get_farmos_url(
                        image["data"]["attributes"]["uri"]["url"]
                    )
                    # nb. other styles available:  medium, wide
                    data["large_image_url"] = image["data"]["attributes"][
                        "image_style_uri"
                    ]["large"]
                    data["thumbnail_image_url"] = image["data"]["attributes"][
                        "image_style_uri"
                    ]["thumbnail"]

        return data

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

    def normalize_animal(self, animal):

        birthdate = animal["attributes"]["birthdate"]
        if birthdate:
            birthdate = datetime.datetime.fromisoformat(birthdate)
            birthdate = self.app.localtime(birthdate)

        return {
            "uuid": animal["id"],
            "drupal_internal_id": animal["attributes"]["drupal_internal__id"],
            "name": animal["attributes"]["name"],
            "species_breed": "",  # TODO
            "birthdate": birthdate,
            "sex": animal["attributes"]["sex"],
            "is_castrated": animal["attributes"]["is_castrated"],
            "location": "",  # TODO
            "status": animal["attributes"]["status"],
            "notes": animal["attributes"]["notes"]["value"],
        }

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

        # is_castrated
        f.set_node("is_castrated", colander.Boolean())

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

        # image
        if url := animal.get("large_image_url"):
            f.set_widget("image", AnimalImage())
            f.set_default("image", url)

    def get_xref_buttons(self, animal):
        return [
            self.make_button(
                "View in farmOS",
                primary=True,
                url=self.app.get_farmos_url(f"/asset/{animal['drupal_internal_id']}"),
                target="_blank",
                icon_left="external-link-alt",
            ),
        ]


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

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


def includeme(config):
    defaults(config)
