# -*- 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/>.
#
################################################################################
"""
Custom form widgets for WuttaFarm
"""

import json

import colander
from deform.widget import Widget
from webhelpers2.html import HTML, tags

from wuttaweb.forms.widgets import WuttaCheckboxChoiceWidget
from wuttaweb.db import Session


class ImageWidget(Widget):
    """
    Widget to display an image URL for a record.
    """

    def __init__(self, alt_text, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.alt_text = alt_text

    def serialize(self, field, cstruct, **kw):
        """ """
        readonly = kw.get("readonly", self.readonly)
        if readonly:
            if cstruct in (colander.null, None):
                return HTML.tag("span")

            return tags.image(cstruct, self.alt_text, **kw)

        return super().serialize(field, cstruct, **kw)


class AnimalTypeWidget(Widget):
    """
    Widget to display an "animal type" field.
    """

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def serialize(self, field, cstruct, **kw):
        """ """
        readonly = kw.get("readonly", self.readonly)
        if readonly:
            if cstruct in (colander.null, None):
                return HTML.tag("span")

            animal_type = json.loads(cstruct)
            return tags.link_to(
                animal_type["name"],
                self.request.route_url(
                    "farmos_animal_types.view", uuid=animal_type["uuid"]
                ),
            )

        return super().serialize(field, cstruct, **kw)


class StructureWidget(Widget):
    """
    Widget to display a "structure" field.
    """

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def serialize(self, field, cstruct, **kw):
        """ """
        readonly = kw.get("readonly", self.readonly)
        if readonly:
            if cstruct in (colander.null, None):
                return HTML.tag("span")

            structure = json.loads(cstruct)
            return tags.link_to(
                structure["name"],
                self.request.route_url(
                    "farmos_structures.view", uuid=structure["uuid"]
                ),
            )

        return super().serialize(field, cstruct, **kw)


class UsersWidget(Widget):
    """
    Widget to display the list of owners for an asset etc.
    """

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def serialize(self, field, cstruct, **kw):
        """ """
        readonly = kw.get("readonly", self.readonly)
        if readonly:
            if cstruct in (colander.null, None):
                return HTML.tag("span")

            items = []
            for user in json.loads(cstruct):
                link = tags.link_to(
                    user["display_name"],
                    self.request.route_url("farmos_users.view", uuid=user["uuid"]),
                )
                items.append(HTML.tag("li", c=link))

            return HTML.tag("ul", c=items)

        return super().serialize(field, cstruct, **kw)


class AssetParentRefsWidget(WuttaCheckboxChoiceWidget):
    """
    Widget for Parents field which references assets.
    """

    def serialize(self, field, cstruct, **kw):
        """ """
        model = self.app.model
        session = Session()

        readonly = kw.get("readonly", self.readonly)
        if readonly:
            parents = []
            for uuid in json.loads(cstruct):
                parent = session.get(model.Asset, uuid)
                parents.append(
                    HTML.tag(
                        "li",
                        c=tags.link_to(
                            str(parent),
                            self.request.route_url(
                                f"{parent.asset_type}_assets.view", uuid=parent.uuid
                            ),
                        ),
                    )
                )
            return HTML.tag("ul", c=parents)

        return super().serialize(field, cstruct, **kw)
