from telegram.ext._callbackcontext import CallbackContext
from telegram import Bot, Update
from django.core.cache import cache
from bot.component.paginator import PaginatorOutput
from bot.models import User
import os,json,logging
from dotenv import load_dotenv
from django.conf import settings
load_dotenv()
from telegram.ext import filters
from glob import glob
from pathlib import Path


class Texts:
    def __init__(self,languages,language):
        self.languages=languages
        self.language=language
        self.texts={}
        self.load_texts()

    def load_texts(self)->None:
        if cached:=cache.get(f'bot_texts', None):
            self.texts = cached
            return
        django_root = Path(settings.BASE_DIR)
        bot_panel_dir = django_root /os.getenv('PANEL_DIR')
        out = {}
        for lang in self.languages:
            data={}
            p = bot_panel_dir/f'texts/{lang}'
            for i in glob(f'{p}/*.json'):
                with open(i, 'r') as f:
                    items = f.read()
                    data.update(json.loads(items))
            out[lang] = data
        cache.set(f'bot_texts', out, timeout=60)
        self.texts = out

    def __call__(self, key):
        out= self.texts[self.language].get(key, key)
        return out


class BaseBot:
    def __init__(self, name):
        self._name = name
        self._level = name
        self.bot: Bot = None
        self.update: Update = None
        self.context: CallbackContext = None
        self.user: User = None
        self.setting = None
        self.method_prefix = os.getenv('BOT_METHODE_PREFIX') or "n_"
        self.menu_btns = []
        self.menu_btns_pattern = 3
        self.admins = []
        self.chat_filters = filters.ChatType.PRIVATE
        self.allow_continue = True
        self._handlers = []
        self._set_users_level()
        self.__pagination: dict[str, PaginatorOutput] = {}
        self.chat_id = None
        self.user_id = None
        self.message_id = None
        self.text = None
        self.message_type = 'text'
        self.languages = User.LANGUAGES
        self.language = os.getenv('DEFAULT_LANGUAGE')
        self.T: Texts = Texts(self.languages,self.language)

        self.entry_MH_filters = []
    def _set_users_level(self,empty_cache=False):
        if empty_cache:cache.delete('users_level')
        users_level = cache.get(f'users_level')
        if not users_level:
            try:
                print('run set_users_level')
                users_level = User.objects.all().values_list('user_id', 'level')
                if users_level:
                    users_level = {user_id: level_id for user_id, level_id in users_level}
                    cache.set('users_level', users_level, 1800)
            except Exception as e:
                print(e)
