# -*- 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 Quick Form views
"""

import logging

from pyramid.renderers import render_to_response

from wuttaweb.views import View
from wuttaweb.db import Session

from wuttafarm.web.util import get_farmos_client_for_user


log = logging.getLogger(__name__)


class QuickFormView(View):
    """
    Base class for quick form views.
    """

    Session = Session

    def __init__(self, request, context=None):
        super().__init__(request, context=context)
        self.farmos_client = get_farmos_client_for_user(self.request)
        self.farmos_4x = self.app.is_farmos_4x(self.farmos_client)
        self.normal = self.app.get_normalizer(self.farmos_client)

    @classmethod
    def get_route_slug(cls):
        return cls.route_slug

    @classmethod
    def get_url_slug(cls):
        return cls.url_slug

    @classmethod
    def get_form_title(cls):
        return cls.form_title

    def __call__(self):
        form = self.make_quick_form()

        if form.validate():
            try:
                result = self.save_quick_form(form)
            except Exception as err:
                log.warning("failed to save 'edit' form", exc_info=True)
                self.request.session.flash(
                    f"Save failed: {self.app.render_error(err)}", "error"
                )
            else:
                return self.redirect_after_save(result)

        return self.render_to_response({"form": form})

    def make_quick_form(self):
        raise NotImplementedError

    def save_quick_form(self, form):
        raise NotImplementedError

    def redirect_after_save(self, result):
        return self.redirect(self.request.current_route_url())

    def render_to_response(self, context):

        defaults = {
            "index_title": "Quick Form",
            "form_title": self.get_form_title(),
            "help_text": self.__doc__.strip(),
        }

        defaults.update(context)
        context = defaults

        # supplement context further if needed
        context = self.get_template_context(context)

        page_templates = self.get_page_templates()
        mako_path = page_templates[0]
        try:
            render_to_response(mako_path, context, request=self.request)
        except IOError:

            # try one or more fallback templates
            for fallback in page_templates[1:]:
                try:
                    return render_to_response(fallback, context, request=self.request)
                except IOError:
                    pass

            # if we made it all the way here, then we found no
            # templates at all, in which case re-attempt the first and
            # let that error raise on up
            return render_to_response(mako_path, context, request=self.request)

    def get_page_templates(self):
        route_slug = self.get_route_slug()
        page_templates = [f"/quick/{route_slug}.mako"]
        page_templates.extend(self.get_fallback_templates())
        return page_templates

    def get_fallback_templates(self):
        return ["/quick/form.mako"]

    def get_template_context(self, context):
        return context

    @classmethod
    def defaults(cls, config):
        cls._defaults(config)

    @classmethod
    def _defaults(cls, config):
        route_slug = cls.get_route_slug()
        url_slug = cls.get_url_slug()
        form_title = cls.get_form_title()

        config.add_wutta_permission("quick", f"quick.{route_slug}", form_title)
        config.add_route(f"quick.{route_slug}", f"/quick/{url_slug}")
        config.add_view(
            cls, route_name=f"quick.{route_slug}", permission=f"quick.{route_slug}"
        )
