import os
import threading
import time

from telegram.ext import Updater, CommandHandler, MessageHandler
from telegram.error import TimedOut
import random


class EfiChat:

    def __init__(self, token):
        self.delays = {}

        updater = Updater(str(token))
        dp = updater.dispatcher
        dp.add_handler(CommandHandler('delay', self.delay))
        dp.add_handler(MessageHandler(filters=None, callback=self.on_message))
        updater.start_polling()
        updater.idle()

    def on_message(self, bot, update):
        chat_id = update.effective_message.chat_id
        message_id = update.effective_message.message_id

        thread = threading.Thread(
            name=chat_id,
            target=self.delete_message,
            args=(
                bot,
                chat_id,
                message_id,
                self.get_delay(chat_id)
            )
        )
        thread.start()

    def get_delay(self, chat_id):

        if chat_id not in self.delays:
            self.delays[chat_id] = None

        elif 'random' == self.delays[chat_id]:
            return random.randint(0, 10) * 3

        elif type(self.delays[chat_id]) is int:
            return self.delays[chat_id]

        return None

    @staticmethod
    def delete_message(bot, chat_id, message_id, delay):

        if delay:
            time.sleep(delay)
            bot.deleteMessage(chat_id, message_id)

    def delay(self, bot, update):
        chat_id = update.effective_message.chat_id
        message_id = update.effective_message.message_id

        value = self.valid_delay(
            update.effective_message.text.replace('/delay ', '')
        )

        if value:
            self.delays[chat_id] = value

        thread = threading.Thread(
            name=chat_id,
            target=self.delete_message,
            args=(
                bot,
                chat_id,
                message_id,
                self.get_delay(chat_id)
            )
        )
        thread.start()

    @staticmethod
    def valid_delay(value):
        try:
            return int(value)
        except ValueError:

            if value == 'random':
                return 'random'


if __name__ == '__main__':
    TOKEN = os.getenv('TOKEN', None)

    if TOKEN:
        EfiChat(TOKEN)
