# mautrix-amp - A hacky Matrix-SMS bridge using the JS from Android Messages for Web
# Copyright (C) 2021 Tulir Asokan
#
# 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 typing import Optional, ClassVar, TYPE_CHECKING

from attr import dataclass

from mautrix.util.async_db import Database

fake_db = Database("") if TYPE_CHECKING else None


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

    user_id: int
    number: Optional[str]
    name: Optional[str]
    is_registered: bool

    async def insert(self) -> None:
        q = "INSERT INTO puppet (user_id, number, name, is_registered) VALUES ($1, $2, $3, $4)"
        await self.db.execute(q, self.user_id, self.number, self.name, self.is_registered)

    async def update(self) -> None:
        q = "UPDATE puppet SET number=$2, name=$3, is_registered=$4 WHERE user_id=$1"
        await self.db.execute(q, self.user_id, self.number, self.name, self.is_registered)

    @classmethod
    async def get_by_user_id(cls, user_id: int) -> Optional['Puppet']:
        q = "SELECT user_id, number, name, is_registered FROM puppet WHERE user_id=$1"
        row = await cls.db.fetchrow(q, user_id)
        if not row:
            return None
        return cls(**row)