# Written by retoor@molodetz.nl

# This code defines a WebView class that inherits from BaseView and includes a method for rendering a web template, requiring login access for its usage.

# The code imports the BaseView class from the `snek.system.view` module.

# 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.system.view import BaseView


class WebView(BaseView):
    login_required = True

    async def get(self):
        if self.login_required and not self.session.get("logged_in"):
            return web.HTTPFound("/")
        channel = await self.services.channel.get(
            uid=self.request.match_info.get("channel")
        )
        if not channel:
            user = await self.services.user.get(
                uid=self.request.match_info.get("channel")
            )
            if user:
                channel = await self.services.channel.get_dm(
                    self.session.get("uid"), user["uid"]
                )
                if channel:
                    return web.HTTPFound("/channel/{}.html".format(channel["uid"]))
        if not channel:
            return web.HTTPNotFound()

        channel_member = await self.app.services.channel_member.get(
            user_uid=self.session.get("uid"), channel_uid=channel["uid"]
        )
        if not channel_member:
            if not channel["is_private"]:
                channel_member = await self.app.services.channel_member.create(
                    channel_uid=channel["uid"],
                    user_uid=self.session.get("uid"),
                    is_moderator=False,
                    is_read_only=False,
                    is_muted=False,
                    is_banned=False,
                )

            return web.HTTPNotFound()

        channel_member["new_count"] = 0
        await self.app.services.channel_member.save(channel_member)

        user = await self.services.user.get(uid=self.session.get("uid"))
        messages = [
            await self.app.services.channel_message.to_extended_dict(message)
            for message in await self.app.services.channel_message.offset(
                channel["uid"]
            )
        ]
        for message in messages:
            await self.app.services.notification.mark_as_read(
                self.session.get("uid"), message["uid"]
            )

        name = await channel_member.get_name()
        return await self.render_template(
            "web.html",
            {"name": name, "channel": channel, "user": user, "messages": messages},
        )
