from django.db import models
from django.utils import timezone
# from django.apps import apps
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings

from ..registry import sync_registry
import uuid

from . import ModelLog, SideStoreModel, BaseModel

class DataAccess(BaseModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4)
    # owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='owned_data', on_delete=models.CASCADE)
    shared_with = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='shared_data')
    model_name = models.CharField(max_length=50)
    model_id = models.UUIDField()
    granted_at = models.DateTimeField(auto_now_add=True)
    # last_hierarchy_update = models.DateTimeField(default=timezone.now)

    def create_revoke_access_log(self):
        self.create_access_log(self.shared_with.all(), 'REVOKE_ACCESS')

    def concerned_users(self):
        users = list(self.shared_with.all())
        if self.related_user:
            users.append(self.related_user)
        return users

    def create_access_log(self, users, operation):
        """Create an access log for a list of users """
        model_class = sync_registry.get_model(self.model_name)
        if model_class:
            try:
                obj = model_class.objects.get(id=self.model_id)
                store_id = None
                if isinstance(obj, SideStoreModel):
                    store_id = obj.store_id

                for user in users:
                    existing_log = ModelLog.objects.filter(user=user, model_id=self.model_id, operation=operation).first()
                    if existing_log:
                        existing_log.date = timezone.now()
                        existing_log.model_operation = operation
                        existing_log.save()
                    else:
                        ModelLog.objects.create(
                            user=user,
                            model_id=self.model_id,
                            model_name=self.model_name,
                            operation=operation,
                            date=timezone.now(),
                            store_id=store_id
                        )
            except ObjectDoesNotExist:
                pass
        else:
            print(f'model not found: {self.model_name}')
