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

import datetime

import colander

from wuttaweb.forms.schema import WuttaDateTime

from wuttafarm.web.views.farmos import FarmOSMasterView


class UserView(FarmOSMasterView):
    """
    Master view for Farm Animals
    """

    model_name = "farmos_user"
    model_title = "farmOS User"
    model_title_plural = "farmOS Users"

    route_prefix = "farmos_users"
    url_prefix = "/farmOS/users"

    farmos_refurl_path = "/people"

    grid_columns = [
        "display_name",
    ]

    sort_defaults = "display_name"

    form_fields = [
        "display_name",
        "name",
        "mail",
        "timezone",
        "created",
        "changed",
    ]

    def get_grid_data(self, columns=None, session=None):
        users = self.farmos_client.resource.get("user", "user")
        return [self.normalize_user(u) for u in users["data"]]

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

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

    def get_instance(self):
        user = self.farmos_client.resource.get_id(
            "user", "user", self.request.matchdict["uuid"]
        )
        self.raw_json = user
        return self.normalize_user(user["data"])

    def get_instance_title(self, user):
        return user["display_name"]

    def normalize_user(self, user):

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

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

        return {
            "uuid": user["id"],
            "drupal_id": user["attributes"].get("drupal_internal__uid"),
            "display_name": user["attributes"]["display_name"],
            "name": user["attributes"].get("name") or colander.null,
            "mail": user["attributes"].get("mail") or colander.null,
            "timezone": user["attributes"].get("timezone") or colander.null,
            "created": created,
            "changed": changed,
        }

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

        # created
        f.set_node("created", WuttaDateTime())

        # changed
        f.set_node("changed", WuttaDateTime())

    def get_xref_buttons(self, user):
        model = self.app.model
        session = self.Session()
        buttons = []

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

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

        return buttons


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

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


def includeme(config):
    defaults(config)
