# Written by retoor@molodetz.nl

# This code implements a web view feature for searching users. It handles GET requests to retrieve user data based on a search query and also processes form submissions.

# Imports used that are not part of the Python language:
# - aiohttp: Used to handle asynchronous web server functionalities.
# - snek.form.search_user: Contains the definition for SearchUserForm, a form specific to searching users.
# - snek.system.view: Provides the BaseFormView class to facilitate form-related operations in a web context.

# MIT License
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


from aiohttp import web
from snek.form.search_user import SearchUserForm
from snek.system.view import BaseFormView


class SearchUserView(BaseFormView):
    form = SearchUserForm

    async def get(self):
        users = []
        query = self.request.query.get("query")
        if query:
            users = await self.app.services.user.search(query)

        if self.request.path.endswith(".json"):
            return await super().get()

        return await self.render_template("search_user.html", {"users": users, "query": query or ''})

    async def submit(self, form):
        if await form.is_valid:
            return {"redirect_url": "/search-user.html?query=" + form['username']}
        return {"is_valid": False}