# -*- 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 collections import OrderedDict

from webhelpers2.html import tags

from wuttaweb.forms.schema import WuttaDictEnum
from wuttaweb.forms.widgets import WuttaDateTimeWidget
from wuttaweb.util import get_form_data

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
from wuttafarm.web.util import get_farmos_client_for_user


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

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

    farmos_entity_type = "taxonomy_term"
    farmos_bundle = "animal_type"
    farmos_refurl_path = "/admin/structure/taxonomy/manage/animal_type/overview"

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

    sort_defaults = "name"

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

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

    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 delete(self):
        animal_type = self.get_instance()

        if animal_type.animal_assets:
            self.request.session.flash(
                "Cannot delete animal type which is still referenced by animal assets.",
                "warning",
            )
            url = self.get_action_url("view", animal_type)
            return self.redirect(self.request.get_referrer(default=url))

        return super().delete()

    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)
        g.filters["sex"].verbs = ["equal", "not_equal"]

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

    def ajax_create(self):
        """
        AJAX view to create a new animal type.
        """
        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"}

        animal_type = model.AnimalType(name=name)
        session.add(animal_type)
        session.flush()

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

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

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

    @classmethod
    def _animal_type_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",
        )


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

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

    farmos_refurl_path = "/assets/animal"
    farmos_bundle = "animal"

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

    grid_columns = [
        "thumbnail",
        "drupal_id",
        "asset_name",
        "produces_eggs",
        "animal_type",
        "birthdate",
        "is_sterile",
        "sex",
        "groups",
        "owners",
        "locations",
        "archived",
    ]

    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)
        if self.farmos_style_grid_links:
            g.set_renderer("animal_type", self.render_animal_type_for_grid)
        else:
            g.set_link("animal_type")

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

        # sex
        g.set_enum("sex", enum.ANIMAL_SEX)
        g.filters["sex"].verbs = ["equal", "not_equal"]

    def render_animal_type_for_grid(self, animal, field, value):
        url = self.request.route_url("animal_types.view", uuid=animal.animal_type_uuid)
        return tags.link_to(value, url)

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

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

        # birthdate
        f.fields.insert_after("animal_type", "birthdate")
        # TODO: why must we assign the widget here?  pretty sure that
        # was not needed when we declared form_fields directly, i.e.
        # instead of adding birthdate field in this method
        f.set_widget("birthdate", WuttaDateTimeWidget(self.request))

        # produces_eggs
        f.fields.insert_after("birthdate", "produces_eggs")

        # sex
        f.fields.insert_after("produces_eggs", "sex")
        if not (self.creating or self.editing) and animal.sex is None:
            pass  # TODO: dict enum widget does not handle null values well
        else:
            # nb. ensure empty option appears like we want
            sex_enum = OrderedDict([("", "N/A")] + list(enum.ANIMAL_SEX.items()))
            f.set_node("sex", WuttaDictEnum(self.request, sex_enum))
            f.set_required("sex", False)

        # is_sterile
        f.fields.insert_after("sex", "is_sterile")


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)
