# -*- 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 Quantity Types
"""

import datetime

import colander

from wuttaweb.forms.schema import WuttaDateTime
from wuttaweb.forms.widgets import WuttaDateTimeWidget

from wuttafarm.web.views.farmos import FarmOSMasterView
from wuttafarm.web.forms.schema import FarmOSUnitRef


class QuantityTypeView(FarmOSMasterView):
    """
    View for farmOS Quantity Types
    """

    model_name = "farmos_quantity_type"
    model_title = "farmOS Quantity Type"
    model_title_plural = "farmOS Quantity Types"

    route_prefix = "farmos_quantity_types"
    url_prefix = "/farmOS/quantity-types"

    grid_columns = [
        "label",
        "description",
    ]

    sort_defaults = "label"

    form_fields = [
        "label",
        "description",
    ]

    def get_grid_data(self, columns=None, session=None):
        result = self.farmos_client.resource.get("quantity_type")
        return [self.normalize_quantity_type(t) for t in result["data"]]

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

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

        # description
        g.set_searchable("description")

    def get_instance(self):
        result = self.farmos_client.resource.get_id(
            "quantity_type", "quantity_type", self.request.matchdict["uuid"]
        )
        self.raw_json = result
        return self.normalize_quantity_type(result["data"])

    def get_instance_title(self, quantity_type):
        return quantity_type["label"]

    def normalize_quantity_type(self, quantity_type):
        return {
            "uuid": quantity_type["id"],
            "drupal_id": quantity_type["attributes"]["drupal_internal__id"],
            "label": quantity_type["attributes"]["label"],
            "description": quantity_type["attributes"]["description"],
        }

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

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

    def get_xref_buttons(self, quantity_type):
        model = self.app.model
        session = self.Session()
        buttons = []

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

        return buttons


class QuantityMasterView(FarmOSMasterView):
    """
    Base class for Quantity views
    """

    farmos_quantity_type = None

    grid_columns = [
        "measure",
        "value",
        "label",
        "changed",
    ]

    sort_defaults = ("changed", "desc")

    form_fields = [
        "measure",
        "value",
        "units",
        "label",
        "created",
        "changed",
    ]

    def get_grid_data(self, columns=None, session=None):
        result = self.farmos_client.resource.get("quantity", self.farmos_quantity_type)
        return [self.normalize_quantity(t) for t in result["data"]]

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

        # value
        g.set_link("value")

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

    def get_instance(self):
        quantity = self.farmos_client.resource.get_id(
            "quantity", self.farmos_quantity_type, self.request.matchdict["uuid"]
        )
        self.raw_json = quantity

        data = self.normalize_quantity(quantity["data"])

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

            # add units
            if units := relationships.get("units"):
                if units["data"]:
                    unit = self.farmos_client.resource.get_id(
                        "taxonomy_term", "unit", units["data"]["id"]
                    )
                    data["units"] = {
                        "uuid": unit["data"]["id"],
                        "name": unit["data"]["attributes"]["name"],
                    }

        return data

    def get_instance_title(self, quantity):
        return quantity["value"]

    def normalize_quantity(self, quantity):

        if created := quantity["attributes"]["created"]:
            created = datetime.datetime.fromisoformat(created)
            created = self.app.localtime(created)

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

        return {
            "uuid": quantity["id"],
            "drupal_id": quantity["attributes"]["drupal_internal__id"],
            "measure": quantity["attributes"]["measure"],
            "value": quantity["attributes"]["value"],
            "label": quantity["attributes"]["label"] or colander.null,
            "created": created,
            "changed": changed,
        }

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

        # created
        f.set_node("created", WuttaDateTime(self.request))
        f.set_widget("created", WuttaDateTimeWidget(self.request))

        # changed
        f.set_node("changed", WuttaDateTime(self.request))
        f.set_widget("changed", WuttaDateTimeWidget(self.request))

        # units
        f.set_node("units", FarmOSUnitRef())


class StandardQuantityView(QuantityMasterView):
    """
    View for farmOS Standard Quantities
    """

    model_name = "farmos_standard_quantity"
    model_title = "farmOS Standard Quantity"
    model_title_plural = "farmOS Standard Quantities"

    route_prefix = "farmos_quantities_standard"
    url_prefix = "/farmOS/quantities/standard"

    farmos_quantity_type = "standard"

    def get_xref_buttons(self, standard_quantity):
        model = self.app.model
        session = self.Session()
        buttons = []

        if wf_standard_quantity := (
            session.query(model.StandardQuantity)
            .join(model.Quantity)
            .filter(model.Quantity.farmos_uuid == standard_quantity["uuid"])
            .first()
        ):
            buttons.append(
                self.make_button(
                    f"View {self.app.get_title()} record",
                    primary=True,
                    url=self.request.route_url(
                        "quantities_standard.view", uuid=wf_standard_quantity.uuid
                    ),
                    icon_left="eye",
                )
            )

        return buttons


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

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

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


def includeme(config):
    defaults(config)
