# BFH Science Self-Service Portal
# Copyright (C) 2025-2026 IKUS Software
#
# This program 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.
#
# This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.

import cherrypy
from cherrypy_foundation.form import CherryForm
from cherrypy_foundation.tools.i18n import gettext_lazy as _
from wtforms.fields import BooleanField
from wtforms.validators import InputRequired

from bfh_science_ssp.core.const import LNI_CLOUD


class EnableOpenStackForm(CherryForm):
    """
    Form used to enable access to OpenStack.
    """

    subject = _('Enable OpenStack Access')

    # Need to check with Daniel if any information is required to enable OpenStack Access.
    accept = BooleanField(
        label=_('I understand FIXME.'),
        validators=[
            InputRequired(),
        ],
    )


class CloudHandler:

    @cherrypy.expose()
    @cherrypy.tools.json_out()
    def cloud_json(self, u=None, **kwargs):
        """
        Query OpenStack to return a list of cloud resources.
        """
        # Query user's attributes
        user = self._query__user(u)
        # Query openstack directly.
        servers = []
        for project in cherrypy.openstack.get_project_list(user.username):
            for server in cherrypy.openstack.get_server_list(project['id']):
                server['project'] = project
                server['service'] = LNI_CLOUD
                servers.append(server)
        # Query user's cloud resources
        return {'data': servers}

    @cherrypy.expose()
    @cherrypy.tools.allow(methods=['POST'])
    @cherrypy.tools.ratelimit(method=['POST'])
    def enable_openstack(self, u=None, **kwargs):
        """
        Handle OpenStack access.
        """
        cfg = cherrypy.tree.apps[''].cfg
        # Guest user's are not allowed to request access to openstack directly.
        # A request will be sent to ITS.
        currentuser = cherrypy.serving.request.currentuser
        if currentuser.role == currentuser.ROLE_GUEST:
            self._send_request(EnableOpenStackForm())
        else:
            self._exec_request(cfg.enable_openstack_cmd, EnableOpenStackForm())
