from django.contrib.auth.models import AbstractBaseUser
from django.core.cache import cache
from django.conf import settings
import logging
from django.db import models
import os
from dotenv import load_dotenv
load_dotenv()

logger = logging.getLogger(__name__)

class Setting(models.Model):
    key='bot_setting'
    name = models.CharField(max_length=100, default=key)
    status_bot = models.BooleanField(default=True)
    is_maintenance = models.BooleanField(default=False)

    @classmethod
    def get_boolean_fields(cls):
        boolean_fields = {
            field.name: (field.value_from_object(cls.objects.first()), field.verbose_name or field.name)
            for field in cls._meta.fields
            if isinstance(field, models.BooleanField)
        }
        return boolean_fields

    @classmethod
    def get_setting(cls):
        if cache.get(cls.key):
            return cache.get(cls.key)
        out= cls.objects.first()
        cache.set(cls.key, out, 3600 * 24)
        return out

    @classmethod
    def initialize(cls):
        cls.objects.exclude(name=cls.key).delete()
        cache.delete(cls.key)
        setting, created = cls.objects.get_or_create(
            name=Setting.key,
            defaults={}
        )

        return setting

    def save(self, *args, **kwargs):
        cache.delete(self.name)
        super().save(*args, **kwargs)


class User(models.Model):
    user_id = models.BigIntegerField(unique=True, db_index=True)
    username = models.CharField(max_length=255, blank=True, null=True)
    first_name = models.CharField(max_length=255, blank=True, null=True)
    last_name = models.CharField(max_length=255, blank=True, null=True)
    is_active = models.BooleanField(default=True)
    is_banned = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    LANGUAGES = os.getenv('LANGUAGES').split(' ') if os.getenv('LANGUAGES') else ['en']
    BOT_LANGUAGES = [[i,i] for i in LANGUAGES]
    language = models.CharField(max_length=20, choices=BOT_LANGUAGES, null=True,blank=True)
    LEVELS = os.getenv('LEVELS').split(' ') if os.getenv('LEVELS') else ['admin']
    BOT_LEVELS = [[lvl,lvl] for lvl in LEVELS]
    level = models.CharField(max_length=20, choices=BOT_LEVELS, default=os.getenv('DEFAULT_LEVEL'))

    def __str__(self):
        name = self.username
        if name: return name[:10]
        name = self.first_name
        if name: return name[:10]
        name = str(self.user_id)
        if name: return name[:10]

    def empty_cache(self):
        cache.delete(f'{self.user_id}:user')

    def save(self, *args, **kwargs):
        try:
            old_level = cache.get('users_level').get(self.user_id)
            if old_level != self.level:
                print("level changed")
                cache.delete(f'users_level')
        except:
            pass
        super().save(*args, **kwargs)
        self.empty_cache()

