# -*- 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 farmOS Equipment
"""

from webhelpers2.html import tags

from wuttafarm.web.views.farmos.master import TaxonomyMasterView
from wuttafarm.web.views.farmos.assets import AssetMasterView
from wuttafarm.web.forms.schema import FarmOSEquipmentTypeRefs


class EquipmentTypeView(TaxonomyMasterView):
    """
    Master view for Equipment Types in farmOS.
    """

    model_name = "farmos_equipment_type"
    model_title = "farmOS Equipment Type"
    model_title_plural = "farmOS Equipment Types"

    route_prefix = "farmos_equipment_types"
    url_prefix = "/farmOS/equipment-types"

    farmos_taxonomy_type = "equipment_type"
    farmos_refurl_path = "/admin/structure/taxonomy/manage/equipment_type/overview"

    def get_xref_buttons(self, equipment_type):
        buttons = super().get_xref_buttons(equipment_type)
        model = self.app.model
        session = self.Session()

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

        return buttons


class EquipmentAssetView(AssetMasterView):
    """
    Master view for farmOS Equipment Assets
    """

    model_name = "farmos_equipment_assets"
    model_title = "farmOS Equipment Asset"
    model_title_plural = "farmOS Equipment Assets"

    route_prefix = "farmos_equipment_assets"
    url_prefix = "/farmOS/assets/equipment"

    farmos_asset_type = "equipment"
    farmos_refurl_path = "/assets/equipment"

    labels = {
        "equipment_types": "Equipment Type",
    }

    grid_columns = [
        "thumbnail",
        "drupal_id",
        "name",
        "equipment_types",
        "manufacturer",
        "model",
        "serial_number",
        "groups",
        "owners",
        "archived",
    ]

    def get_farmos_api_includes(self):
        includes = super().get_farmos_api_includes()
        includes.update(["equipment_type"])
        return includes

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

        # equipment_types
        g.set_renderer("equipment_types", self.render_equipment_types_for_grid)

    def render_equipment_types_for_grid(self, equipment, field, value):
        if self.farmos_style_grid_links:
            links = []
            for etype in value:
                url = self.request.route_url(
                    f"farmos_equipment_types.view", uuid=etype["uuid"]
                )
                links.append(tags.link_to(etype["name"], url))
            return ", ".join(links)

        return ", ".join([etype["name"] for etype in value])

    def normalize_asset(self, equipment, included):
        data = super().normalize_asset(equipment, included)

        equipment_type_objects = []
        rels = equipment["relationships"]
        for etype in rels["equipment_type"]["data"]:
            uuid = etype["id"]
            equipment_type = {
                "uuid": uuid,
                "type": etype["type"],
            }
            if etype := included.get(uuid):
                equipment_type.update(
                    {
                        "name": etype["attributes"]["name"],
                    }
                )
            equipment_type_objects.append(equipment_type)

        data.update(
            {
                "manufacturer": equipment["attributes"]["manufacturer"],
                "model": equipment["attributes"]["model"],
                "serial_number": equipment["attributes"]["serial_number"],
                "equipment_types": equipment_type_objects,
            }
        )

        return data

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

        # equipment_types
        f.fields.insert_after("name", "equipment_types")
        f.set_node("equipment_types", FarmOSEquipmentTypeRefs(self.request))

        # manufacturer
        f.fields.insert_after("equipment_types", "manufacturer")

        # model
        f.fields.insert_after("manufacturer", "model")

        # serial_number
        f.fields.insert_after("model", "serial_number")

    def get_xref_buttons(self, equipment):
        model = self.app.model
        session = self.Session()

        buttons = super().get_xref_buttons(equipment)

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

        return buttons


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

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

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


def includeme(config):
    defaults(config)
