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

import datetime

import colander

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

from wuttafarm.web.views.farmos import FarmOSMasterView


class LandAssetView(FarmOSMasterView):
    """
    View for farmOS Land Assets
    """

    model_name = "farmos_land_asset"
    model_title = "farmOS Land Asset"
    model_title_plural = "farmOS Land Assets"

    route_prefix = "farmos_land_assets"
    url_prefix = "/farmOS/land"

    farmos_refurl_path = "/assets/land"

    grid_columns = [
        "name",
        "land_type",
        "is_fixed",
        "is_location",
        "archived",
        "changed",
    ]

    sort_defaults = "name"

    form_fields = [
        "name",
        "land_type",
        "is_fixed",
        "is_location",
        "archived",
        "notes",
        "created",
        "changed",
    ]

    def get_grid_data(self, columns=None, session=None):
        land_assets = self.farmos_client.resource.get("asset", "land")
        return [self.normalize_land_asset(l) for l in land_assets["data"]]

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

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

        # is_fixed
        g.set_renderer("is_fixed", "boolean")

        # is_location
        g.set_renderer("is_location", "boolean")

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

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

        # archived
        g.set_renderer("archived", "boolean")

    def get_instance(self):
        land_asset = self.farmos_client.resource.get_id(
            "asset", "land", self.request.matchdict["uuid"]
        )
        self.raw_json = land_asset
        return self.normalize_land_asset(land_asset["data"])

    def get_instance_title(self, land_asset):
        return land_asset["name"]

    def normalize_land_asset(self, land):

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

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

        if notes := land["attributes"]["notes"]:
            notes = notes["value"]

        if self.farmos_4x:
            archived = land["attributes"]["archived"]
        else:
            archived = land["attributes"]["status"] == "archived"

        return {
            "uuid": land["id"],
            "drupal_id": land["attributes"]["drupal_internal__id"],
            "name": land["attributes"]["name"],
            "land_type": land["attributes"]["land_type"],
            "created": created,
            "changed": changed,
            "is_fixed": land["attributes"]["is_fixed"],
            "is_location": land["attributes"]["is_location"],
            "archived": archived,
            "notes": notes or colander.null,
        }

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

        # is_fixed
        f.set_node("is_fixed", colander.Boolean())

        # is_location
        f.set_node("is_location", colander.Boolean())

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

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

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

        # archived
        f.set_node("archived", colander.Boolean())

    def get_xref_buttons(self, land):
        return [
            self.make_button(
                "View in farmOS",
                primary=True,
                url=self.app.get_farmos_url(f"/asset/{land['drupal_id']}"),
                target="_blank",
                icon_left="external-link-alt",
            ),
        ]

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

        buttons = [
            self.make_button(
                "View in farmOS",
                primary=True,
                url=self.app.get_farmos_url(f"/asset/{land['drupal_id']}"),
                target="_blank",
                icon_left="external-link-alt",
            ),
        ]

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

        return buttons


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

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


def includeme(config):
    defaults(config)
