# -*- coding: utf-8 -*-

import logging
from traceback import format_exc

from libbot import config_get, json_read
from pyrogram import filters
from pyrogram.client import Client
from pyrogram.enums.chat_action import ChatAction
from pyrogram.types import Message

from modules.utils import string, userGet
from modules.bwt import getWaterLeft

logger = logging.getLogger(__name__)


@Client.on_message(
    ~filters.scheduled & filters.command(["balance", "баланс"], prefixes=["/", ""])  # type: ignore
)
async def command_balance(app: Client, msg: Message):
    try:
        if "card" in (await json_read("data/database.json"))[str(msg.from_user.id)]:
            await app.send_chat_action(chat_id=msg.chat.id, action=ChatAction.TYPING)
            water_left = await getWaterLeft(
                userGet(msg.from_user.id, "card"), msg.from_user.id, app
            )
            if water_left == "":
                await msg.reply_text(
                    (await string("error_new")).format(
                        f'https://bwtaqua.com.ua/card-topup/?id={userGet(msg.from_user.id, "card")}'
                    )
                )
                # raise EmptyCardException("Card information is empty")
            elif water_left == "Failure":
                await msg.reply_text(
                    (await string("error_occured")).format(await string("get_number"))
                )
                logger.warning(
                    f"User {str(msg.from_user.id)} could not get left water amount"
                )
            else:
                await msg.reply_text((await string("card_balance")).format(water_left))
                logger.info(
                    f"User {str(msg.from_user.id)} has {water_left} liters remaining"
                )
        else:
            await msg.reply_text(
                (await string("card_not_linked")).format(await string("get_number"))
            )
            logger.info(
                f"User {str(msg.from_user.id)} tried to get balance without card set"
            )
    except Exception as exp:
        if msg.from_user.id != await config_get("owner_id"):
            await msg.reply_text(
                (await string("error_occured")).format(await string("get_number"))
            )
        await app.send_message(
            await config_get("owner_id"),
            f"Error occured by {str(msg.from_user.id)}:\nException: `{exp}`\nTraceback: `{format_exc()}`",
        )
        logger.warning(f"User {str(msg.from_user.id)} could not get left water amount")
