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

from wuttaweb.forms.schema import WuttaDictEnum

from wuttafarm.db.model import AnimalType, AnimalAsset
from wuttafarm.web.views.assets import AssetTypeMasterView, AssetMasterView
from wuttafarm.web.forms.schema import AnimalTypeRef
from wuttafarm.web.forms.widgets import ImageWidget


class AnimalTypeView(AssetTypeMasterView):
    """
    Master view for Animal Types
    """

    model_class = AnimalType
    route_prefix = "animal_types"
    url_prefix = "/animal-types"

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

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

    sort_defaults = "name"

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

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

    has_rows = True
    row_model_class = AnimalAsset
    rows_viewable = True

    row_grid_columns = [
        "asset_name",
        "sex",
        "is_sterile",
        "birthdate",
        "archived",
    ]

    rows_sort_defaults = "asset_name"

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

        # name
        g.set_link("name")

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

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

        if animal_type.farmos_uuid:
            buttons.append(
                self.make_button(
                    "View farmOS record",
                    primary=True,
                    url=self.request.route_url(
                        "farmos_animal_types.view", uuid=animal_type.farmos_uuid
                    ),
                    icon_left="eye",
                )
            )

        return buttons

    def get_row_grid_data(self, animal_type):
        model = self.app.model
        session = self.Session()
        return (
            session.query(model.AnimalAsset)
            .join(model.Asset)
            .filter(model.AnimalAsset.animal_type == animal_type)
        )

    def configure_row_grid(self, grid):
        g = grid
        super().configure_row_grid(g)
        model = self.app.model
        enum = self.app.enum

        # asset_name
        g.set_link("asset_name")
        g.set_sorter("asset_name", model.Asset.asset_name)
        g.set_filter("asset_name", model.Asset.asset_name)

        # sex
        g.set_enum("sex", enum.ANIMAL_SEX)

        # archived
        g.set_renderer("archived", "boolean")
        g.set_sorter("archived", model.Asset.archived)
        g.set_filter("archived", model.Asset.archived)

    def get_row_action_url_view(self, animal, i):
        return self.request.route_url("animal_assets.view", uuid=animal.uuid)


class AnimalAssetView(AssetMasterView):
    """
    Master view for Animal Assets
    """

    model_class = AnimalAsset
    route_prefix = "animal_assets"
    url_prefix = "/assets/animal"

    farmos_refurl_path = "/assets/animal"

    labels = {
        "animal_type": "Species/Breed",
        "is_sterile": "Sterile",
    }

    grid_columns = [
        "thumbnail",
        "drupal_id",
        "asset_name",
        "animal_type",
        "birthdate",
        "is_sterile",
        "sex",
        "archived",
    ]

    form_fields = [
        "asset_name",
        "animal_type",
        "birthdate",
        "sex",
        "is_sterile",
        "notes",
        "asset_type",
        "archived",
        "farmos_uuid",
        "drupal_id",
        "thumbnail_url",
        "image_url",
        "thumbnail",
        "image",
    ]

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

        # animal_type
        g.set_joiner("animal_type", lambda q: q.join(model.AnimalType))
        g.set_sorter("animal_type", model.AnimalType.name)
        g.set_filter("animal_type", model.AnimalType.name)

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

        # sex
        g.set_enum("sex", enum.ANIMAL_SEX)

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

        # animal_type
        f.set_node("animal_type", AnimalTypeRef(self.request))

        # sex
        if self.viewing and animal.sex is None:
            pass  # TODO: dict enum widget does not handle null values well
        else:
            f.set_node("sex", WuttaDictEnum(self.request, enum.ANIMAL_SEX))
            f.set_required("sex", False)


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

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

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


def includeme(config):
    defaults(config)
