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

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.widgets import ImageWidget


class StructureView(FarmOSMasterView):
    """
    View for farmOS Structures
    """

    model_name = "farmos_structure_asset"
    model_title = "farmOS Structure"
    model_title_plural = "farmOS Structures"

    route_prefix = "farmos_structure_assets"
    url_prefix = "/farmOS/structures"

    farmos_refurl_path = "/assets/structure"

    grid_columns = [
        "name",
        "archived",
        "created",
        "changed",
    ]

    sort_defaults = "name"

    form_fields = [
        "name",
        "archived",
        "structure_type",
        "is_location",
        "is_fixed",
        "notes",
        "created",
        "changed",
        "raw_image_url",
        "large_image_url",
        "thumbnail_image_url",
        "image",
    ]

    def get_grid_data(self, columns=None, session=None):
        structures = self.farmos_client.resource.get("asset", "structure")
        return [self.normalize_structure(s) for s in structures["data"]]

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

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

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

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

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

    def get_instance(self):
        structure = self.farmos_client.resource.get_id(
            "asset", "structure", self.request.matchdict["uuid"]
        )
        self.raw_json = structure
        data = self.normalize_structure(structure["data"])

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

            # add owners
            if owner := relationships.get("owner"):
                data["owners"] = []
                for owner_data in owner["data"]:
                    owner = self.farmos_client.resource.get_id(
                        "user", "user", owner_data["id"]
                    )
                    data["owners"].append(
                        {
                            "uuid": owner["data"]["id"],
                            "display_name": owner["data"]["attributes"]["display_name"],
                        }
                    )

            # add image urls
            if image := relationships.get("image"):
                if image["data"]:
                    image = self.farmos_client.resource.get_id(
                        "file", "file", image["data"][0]["id"]
                    )
                    data["raw_image_url"] = self.app.get_farmos_url(
                        image["data"]["attributes"]["uri"]["url"]
                    )
                    # nb. other styles available:  medium, wide
                    data["large_image_url"] = image["data"]["attributes"][
                        "image_style_uri"
                    ]["large"]
                    data["thumbnail_image_url"] = image["data"]["attributes"][
                        "image_style_uri"
                    ]["thumbnail"]

        return data

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

    def normalize_structure(self, structure):

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

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

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

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

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

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

        # image
        if url := structure.get("large_image_url"):
            f.set_widget("image", ImageWidget("structure image"))
            f.set_default("image", url)

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

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

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

        return buttons


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

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


def includeme(config):
    defaults(config)
