import requests
import logging

from typing import Tuple
from .config import TelegramChatsConfig

_chats = TelegramChatsConfig()
_logger = logging.getLogger(__name__)


def send_message(text: str,
                 chat: str,
                 parse_mode: str = 'HTML',
                 disable_web_page_preview: bool = False,):
    data, token = _send_telegram_data(text, chat, parse_mode, disable_web_page_preview)
    req = requests.post('https://api.telegram.org/bot%s/sendMessage' % token, data=data)
    return req.json()


def send_photo(filename: str, chat: str):
    chat_data = _chats[chat]
    data = {
        'chat_id': chat_data['id'],
    }
    token = chat_data['token']

    url = f'https://api.telegram.org/bot{token}/sendPhoto'
    with open(filename, "rb") as fd:
        req = requests.post(url, data=data, files={"photo": fd})
    return req.json()


def _send_telegram_data(text: str,
                        chat: str,
                        parse_mode: str = None,
                        disable_web_page_preview: bool = False) -> Tuple[dict, str]:
    chat_data = _chats[chat]
    data = {
        'chat_id': chat_data['id'],
        'text': text
    }

    if parse_mode is not None:
        data['parse_mode'] = parse_mode

    if disable_web_page_preview:
        data['disable_web_page_preview'] = 1

    return data, chat_data['token']
