import logging
import threading
import time

import schedule
from telegram import InlineKeyboardMarkup, ParseMode
from telegram.error import BadRequest
from telegram.ext import Updater, CommandHandler, InlineQueryHandler, CallbackQueryHandler

from exceptions import *
from push_information import __init__ as push_init
from vvs import inline_station_search, handle_vvs, handle_multiple_stations_reply
from weather_meteomedia import handle_meteomedia
from weather_openweathermap import __init__ as openweathermap_init
from weather_openweathermap import handle_weather

token_file = open("token", "r")
updater = Updater(token=token_file.read(), use_context=True)
token_file.close()

dispatcher = updater.dispatcher

logging.basicConfig(format='%(acstime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)


def send_message(chat_id: int, message: str):
    dispatcher.bot.send_message(chat_id=chat_id, text=message, disable_notification=True, parse_mode=ParseMode.MARKDOWN)


def edit_message_and_delete_answer(chat_id: int, message_id: int, message: str,
                                   reply_markup: InlineKeyboardMarkup = None):
    dispatcher.bot.delete_message(chat_id=chat_id, message_id=message_id)
    try:
        dispatcher.bot.edit_message_text(chat_id=chat_id, message_id=message_id - 1, text=message,
                                         reply_markup=reply_markup)
    except BadRequest:
        try:
            dispatcher.bot.edit_message_text(chat_id=chat_id, message_id=message_id - 2, text=message,
                                             reply_markup=reply_markup)
        except BadRequest:
            pass


cease_continuous_run = threading.Event()


class ScheduleThread(threading.Thread):
    @classmethod
    def run(cls):
        while not cease_continuous_run.is_set():
            schedule.run_pending()
            time.sleep(10)


def __main__():
    inline_station_search_handler = InlineQueryHandler(inline_station_search)
    dispatcher.add_handler(inline_station_search_handler)
    dispatcher.add_handler(CommandHandler('vvs', handle_vvs))
    dispatcher.add_handler(CommandHandler('meteomedia', handle_meteomedia))
    dispatcher.add_handler(CommandHandler("weather", handle_weather))

    openweathermap_init()
    dispatcher.add_handler(push_init())

    dispatcher.add_error_handler(error_callback)

    dispatcher.add_handler(CallbackQueryHandler(handle_multiple_stations_reply, pattern="^\/vvs"))

    continuous_thread = ScheduleThread()
    continuous_thread.start()

    updater.start_polling()
    updater.idle()

    cease_continuous_run.set()


if __name__ == "__main__":
    __main__()
