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

from webhelpers2.html import HTML, tags

from wuttafarm.db.model import LandType, LandAsset
from wuttafarm.web.views.assets import AssetTypeMasterView, AssetMasterView
from wuttafarm.web.forms.schema import LandTypeRef


class LandTypeView(AssetTypeMasterView):
    """
    Master view for Land Types
    """

    model_class = LandType
    route_prefix = "land_types"
    url_prefix = "/land-types"

    grid_columns = [
        "name",
    ]

    sort_defaults = "name"

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

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

    has_rows = True
    row_model_class = LandAsset
    rows_viewable = True

    row_grid_columns = [
        "asset_name",
        "is_location",
        "is_fixed",
        "archived",
    ]

    rows_sort_defaults = "asset_name"

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

        # name
        g.set_link("name")

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

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

        return buttons

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

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

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

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

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

        # 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, land_asset, i):
        return self.request.route_url("land_assets.view", uuid=land_asset.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 LandAssetView(AssetMasterView):
    """
    Master view for Land Assets
    """

    model_class = LandAsset
    route_prefix = "land_assets"
    url_prefix = "/assets/land"

    farmos_bundle = "land"
    farmos_refurl_path = "/assets/land"

    grid_columns = [
        "thumbnail",
        "drupal_id",
        "asset_name",
        "land_type",
        "parents",
        "archived",
    ]

    form_fields = [
        "asset_name",
        "parents",
        "notes",
        "asset_type",
        "land_type",
        "is_location",
        "is_fixed",
        "archived",
        "drupal_id",
        "farmos_uuid",
    ]

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

        # land_type
        g.set_joiner("land_type", lambda q: q.join(model.LandType))
        g.set_sorter("land_type", model.LandType.name)
        g.set_filter("land_type", model.LandType.name, label="Land Type Name")

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

        # land_type
        f.set_node("land_type", LandTypeRef(self.request))


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

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

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


def includeme(config):
    defaults(config)
