# -*- 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/>.
#
################################################################################
"""
Views for Users
"""

import colander

from wuttaweb.views import users as base


class UserView(base.UserView):
    """
    Custom master view for Users.
    """

    labels = {
        "farmos_uuid": "farmOS UUID",
        "drupal_id": "Drupal ID",
    }

    def get_template_context(self, context):
        context = super().get_template_context(context)

        if self.listing:
            context["farmos_refurl"] = self.app.get_farmos_url("/admin/people")

        return context

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

        # farmos_uuid
        if not self.creating:
            f.fields.append("farmos_uuid")
            f.set_default("farmos_uuid", user.farmos_uuid or colander.null)

        # drupal_id
        if not self.creating:
            f.fields.append("drupal_id")
            f.set_default("drupal_id", user.drupal_id or colander.null)

    def get_xref_buttons(self, user):
        buttons = []

        if user.drupal_id:
            buttons.append(
                self.make_button(
                    "View in farmOS",
                    primary=True,
                    url=self.app.get_farmos_url(f"/user/{user.drupal_id}"),
                    target="_blank",
                    icon_left="external-link-alt",
                )
            )

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

        return buttons


def defaults(config, **kwargs):
    local = globals()
    UserView = kwargs.get("UserView", local["UserView"])
    base.defaults(config, **{"UserView": UserView})


def includeme(config):
    defaults(config)
