# -*- 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/>.
#
################################################################################
"""
Misc. utilities for web app
"""

from pyramid import httpexceptions
from webhelpers2.html import HTML


def get_farmos_client_for_user(request):
    token = request.session.get("farmos.oauth2.token")
    if not token:
        raise httpexceptions.HTTPForbidden()

    # nb. must give a *copy* of the token to farmOS client, since it
    # will mutate it in-place and we don't want that to happen for our
    # original copy in the user session.  (otherwise the auto-refresh
    # will not work correctly for subsequent calls.)
    token = dict(token)

    def token_updater(token):
        save_farmos_oauth2_token(request, token)

    config = request.wutta_config
    app = config.get_app()
    return app.get_farmos_client(token=token, token_updater=token_updater)


def save_farmos_oauth2_token(request, token):
    """
    Common logic for saving the given OAuth2 token within the user
    session.  This function is called from 2 places:

    * :meth:`wuttafarm.web.views.auth.farmos_oauth_callback()`
    * :meth:`wuttafarm.web.views.farmos.master.FarmOSMasterView.get_farmos_client()`
    """
    # nb. we pretend the token expires 1 minute early, to avoid edge
    # cases around token refresh
    token["expires_at"] -= 60

    # save token to user session
    request.session["farmos.oauth2.token"] = token


def use_farmos_style_grid_links(config):
    return config.get_bool(f"{config.appname}.farmos_style_grid_links", default=True)


def render_quantity_objects(quantities):
    items = []
    for quantity in quantities:
        text = render_quantity_object(quantity)
        items.append(HTML.tag("li", c=text))
    return HTML.tag("ul", c=items)


def render_quantity_object(quantity):
    measure = quantity["measure_name"]
    value = quantity["value_decimal"]
    unit = quantity["unit_name"]
    text = f"( {measure} ) {value} {unit}"

    if quantity["quantity_type_id"] == "material":
        materials = ", ".join(
            [mtype.get("name", "???") for mtype in quantity["material_types"]]
        )
        return f"{materials} {text}"

    return text
