# matrix-appservice-kakaotalk - A Matrix-KakaoTalk puppeting bridge.
# Copyright (C) 2022 Tulir Asokan, Andrew Ferrazzutti
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
from __future__ import annotations

from typing import TYPE_CHECKING, ClassVar

from asyncpg import Record
from attr import dataclass, field

from mautrix.types import ContentURI, RoomID, UserID
from mautrix.util.async_db import Database

from ..kt.types.bson import Long
from ..kt.types.channel.channel_type import ChannelType

fake_db = Database.create("") if TYPE_CHECKING else None


@dataclass
class Portal:
    db: ClassVar[Database] = fake_db

    ktid: Long = field(converter=Long)
    kt_receiver: Long = field(converter=Long)
    kt_type: ChannelType
    mxid: RoomID | None
    name: str | None
    description: str | None
    photo_id: str | None
    avatar_url: ContentURI | None
    encrypted: bool
    name_set: bool
    topic_set: bool
    avatar_set: bool
    relay_user_id: UserID | None

    @classmethod
    def _from_row(cls, row: Record) -> Portal:
        return cls(**row)

    @classmethod
    def _from_optional_row(cls, row: Record | None) -> Portal | None:
        return cls._from_row(row) if row is not None else None

    @classmethod
    async def get_by_ktid(cls, ktid: int, kt_receiver: int) -> Portal | None:
        q = """
            SELECT ktid, kt_receiver, kt_type, mxid, name, description, photo_id, avatar_url, encrypted,
                   name_set, avatar_set, relay_user_id
            FROM portal WHERE ktid=$1 AND kt_receiver=$2
        """
        row = await cls.db.fetchrow(q, ktid, kt_receiver)
        return cls._from_optional_row(row)

    @classmethod
    async def get_by_mxid(cls, mxid: RoomID) -> Portal | None:
        q = """
            SELECT ktid, kt_receiver, kt_type, mxid, name, description, photo_id, avatar_url, encrypted,
                   name_set, avatar_set, relay_user_id
            FROM portal WHERE mxid=$1
        """
        row = await cls.db.fetchrow(q, mxid)
        return cls._from_optional_row(row)

    @classmethod
    async def get_all_by_receiver(cls, kt_receiver: int) -> list[Portal]:
        q = """
            SELECT ktid, kt_receiver, kt_type, mxid, name, description, photo_id, avatar_url, encrypted,
                   name_set, avatar_set, relay_user_id
            FROM portal WHERE kt_receiver=$1
        """
        rows = await cls.db.fetch(q, kt_receiver)
        return [cls._from_row(row) for row in rows if row]

    @classmethod
    async def all(cls) -> list[Portal]:
        q = """
            SELECT ktid, kt_receiver, kt_type, mxid, name, description, photo_id, avatar_url, encrypted,
                   name_set, avatar_set, relay_user_id
            FROM portal
        """
        rows = await cls.db.fetch(q)
        return [cls._from_row(row) for row in rows if row]

    @property
    def _values(self):
        return (
            self.ktid,
            self.kt_receiver,
            self.kt_type,
            self.mxid,
            self.name,
            self.description,
            self.photo_id,
            self.avatar_url,
            self.encrypted,
            self.name_set,
            self.avatar_set,
            self.relay_user_id,
        )

    async def insert(self) -> None:
        q = """
        INSERT INTO portal (ktid, kt_receiver, kt_type, mxid, name, description, photo_id, avatar_url,
                            encrypted, name_set, avatar_set, relay_user_id)
        VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
        """
        await self.db.execute(q, *self._values)

    async def delete(self) -> None:
        q = "DELETE FROM portal WHERE ktid=$1 AND kt_receiver=$2"
        await self.db.execute(q, self.ktid, self.kt_receiver)

    async def save(self) -> None:
        q = """
            UPDATE portal SET kt_type=$3, mxid=$4, name=$5, description=$6, photo_id=$7, avatar_url=$8,
                              encrypted=$9, name_set=$10, avatar_set=$11, relay_user_id=$12
            WHERE ktid=$1 AND kt_receiver=$2
        """
        await self.db.execute(q, *self._values)