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

import os
import traceback
from typing import Union
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from functions import *
from modules.app import app
from bs4 import BeautifulSoup

config = jsonLoad("config.json")

class EmptyCardException(Exception):
    pass

async def getWaterLeft(driver: webdriver.Remote, wait: WebDriverWait, cardid: Union[str, int], filename: int):
        
    url = f"https://bwtaqua.com.ua/card-topup/?id={cardid}"
    
    try:

        # driver.execute_script(f"window.open('about:blank', '{filename}');")
        # driver.switch_to.window(f"{filename}")
        driver.get(f"https://bwtaqua.com.ua/card-topup/?id={cardid}")

        wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'js-payment-balance')))

        page_source = driver.page_source

        driver.execute_script("window.stop();")

        with open(f'data/pages/{filename}.html', "w", encoding="utf-8") as f:
            f.write(page_source)

        output = driver.find_element(By.CLASS_NAME, "js-payment-balance").text.replace("Твій баланс ", "").replace(" л", "")
    
        # soup = BeautifulSoup(page_source, 'html.parser')
        # output = (soup.find_all("h3", class_="headline headline_center headline_pink js-payment-balance")[0].getText()).replace("Твій баланс ", "").replace(" л", "")
        
        appendLog(f"Parsed {output} liters of water remaining (user: {filename}, cardid: {cardid})")
     
    except Exception as exp:
        
        appendLog(f"Exception occured: {exp} (user: {filename}, cardid: {cardid})")
        
        if app != None:
            await app.send_message(config["owner_id"], f"**Exception occured:**\n • User: `{filename}`\n • Card: [{cardid}]({url})\n • Exception: `{exp}`\n • Traceback: `{traceback.format_exc()}`", disable_web_page_preview=True)
        else:
            print(f'Exception occured and could not send to user: {exp}')
        
        output = "Failure"
    
    return output
    
if __name__ == "__main__":
    
    cardid = input("Enter card number: ")
    userid = input("Enter Telegram ID (optional): ")
    
    print(f"Card has {str(getWaterLeft(cardid, userid, app=None))} l. left")
