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

from wuttafarm.web.views import WuttaFarmMasterView
from wuttafarm.db.model import Measure, Unit, Quantity


class MeasureView(WuttaFarmMasterView):
    """
    Master view for Measures
    """

    model_class = Measure
    route_prefix = "measures"
    url_prefix = "/measures"

    grid_columns = [
        "ordinal",
        "name",
        "drupal_id",
    ]

    sort_defaults = "ordinal"

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

    form_fields = [
        "ordinal",
        "name",
        "drupal_id",
    ]

    has_rows = True
    row_model_class = Quantity
    rows_viewable = True

    row_labels = {
        "quantity_type_id": "Quantity Type ID",
        "measure_id": "Measure ID",
    }

    row_grid_columns = [
        "drupal_id",
        "as_text",
        "quantity_type",
        "value",
        "units",
        "label",
    ]

    rows_sort_defaults = ("drupal_id", "desc")

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

        # name
        g.set_link("name")

    def get_row_grid_data(self, measure):
        model = self.app.model
        session = self.Session()
        return session.query(model.Quantity).filter(model.Quantity.measure == measure)

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

        # drupal_id
        g.set_label("drupal_id", "ID", column_only=True)

        # as_text
        g.set_renderer("as_text", self.render_as_text_for_grid)
        g.set_link("as_text")

        # value
        g.set_renderer("value", self.render_value_for_grid)

    def render_as_text_for_grid(self, quantity, field, value):
        return quantity.render_as_text(self.config)

    def render_value_for_grid(self, quantity, field, value):
        value = quantity.value_numerator / quantity.value_denominator
        return self.app.render_quantity(value)

    def get_row_action_url_view(self, quantity, i):
        return self.request.route_url(
            f"quantities_{quantity.quantity_type_id}.view", uuid=quantity.uuid
        )

    @classmethod
    def defaults(cls, config):
        """ """
        wutta_config = config.registry.settings.get("wutta_config")
        app = wutta_config.get_app()

        if app.is_farmos_mirror():
            cls.creatable = False
            cls.editable = False
            cls.deletable = False

        cls._defaults(config)


class UnitView(WuttaFarmMasterView):
    """
    Master view for Units
    """

    model_class = Unit
    route_prefix = "units"
    url_prefix = "/units"

    farmos_entity_type = "taxonomy_term"
    farmos_bundle = "unit"
    farmos_refurl_path = "/admin/structure/taxonomy/manage/unit/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 = Quantity
    rows_viewable = True

    row_labels = {
        "quantity_type_id": "Quantity Type ID",
        "measure_id": "Measure ID",
    }

    row_grid_columns = [
        "drupal_id",
        "as_text",
        "quantity_type",
        "measure",
        "value",
        "label",
    ]

    rows_sort_defaults = ("drupal_id", "desc")

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

        # name
        g.set_link("name")

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

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

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

        return buttons

    def get_row_grid_data(self, unit):
        model = self.app.model
        session = self.Session()
        return session.query(model.Quantity).filter(model.Quantity.units == unit)

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

        # drupal_id
        g.set_label("drupal_id", "ID", column_only=True)

        # as_text
        g.set_renderer("as_text", self.render_as_text_for_grid)
        g.set_link("as_text")

        # value
        g.set_renderer("value", self.render_value_for_grid)

    def render_as_text_for_grid(self, quantity, field, value):
        return quantity.render_as_text(self.config)

    def render_value_for_grid(self, quantity, field, value):
        value = quantity.value_numerator / quantity.value_denominator
        return self.app.render_quantity(value)

    def get_row_action_url_view(self, quantity, i):
        return self.request.route_url(
            f"quantities_{quantity.quantity_type_id}.view", uuid=quantity.uuid
        )


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

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

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


def includeme(config):
    defaults(config)
