# -*- 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/>.
#
################################################################################
"""
Base class for farmOS master views
"""

import json

import markdown

from wuttaweb.views import MasterView

from wuttafarm.web.util import save_farmos_oauth2_token


class FarmOSMasterView(MasterView):
    """
    Base class for farmOS master views
    """

    model_key = "uuid"

    creatable = False
    editable = False
    deletable = False

    filterable = False
    sort_on_backend = False
    paginate_on_backend = False

    farmos_refurl_path = None

    labels = {
        "raw_image_url": "Raw Image URL",
        "large_image_url": "Large Image URL",
        "thumbnail_image_url": "Thumbnail Image URL",
    }

    def __init__(self, request, context=None):
        super().__init__(request, context=context)
        self.farmos_client = self.get_farmos_client()
        self.farmos_4x = self.app.is_farmos_4x(self.farmos_client)
        self.raw_json = None

    def get_farmos_client(self):
        token = self.request.session.get("farmos.oauth2.token")
        if not token:
            raise self.forbidden()

        # 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(self.request, token)

        return self.app.get_farmos_client(token=token, token_updater=token_updater)

    def get_fallback_templates(self, template):
        """ """
        templates = super().get_fallback_templates(template)

        if template == "view":
            templates.insert(0, "/farmos/master/view.mako")

        return templates

    def get_template_context(self, context):

        if self.listing and self.farmos_refurl_path:
            context["farmos_refurl"] = self.app.get_farmos_url(self.farmos_refurl_path)

        if self.viewing and self.raw_json:
            context["raw_json"] = self.raw_json
            code = "```json\n" + json.dumps(self.raw_json, indent=2) + "\n```"
            # TODO: this does not seem to be adding syntax highlight
            context["rendered_json"] = markdown.markdown(
                code, extensions=["fenced_code", "codehilite"]
            )

        return context
