from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from guardian.shortcuts import assign_perm, remove_perm
from ldt.ldt_utils.models import Project, Content
from ldt.management.utils import show_progress

User = get_user_model()

def set_default_permissions(verbose=False, is_migration=False, orm=None):
    writer = None
    
    
    if is_migration:
        list_model = {'User': orm['auth.user'],
                      'Group': orm['auth.group'],
                      'Project': orm.Project,
                      'Content': orm.Content
                      }
    else:
        list_model = {'Project': Project,
                  'Content': Content,
                  'User': User,
                  'Group': Group
                  }
    
    everyone, _ = Group.objects.get_or_create(name=settings.PUBLIC_GROUP_NAME)     
     
    if verbose:   
        total = list_model['Project'].objects.count()
        
    for i, proj in enumerate(list_model['Project'].objects.all()):
        
        if proj.state == 2:
            assign_perm('ldt_utils.view_project', everyone, proj)
        else:
            remove_perm('ldt_utils.view_project', everyone, proj)
        
        assign_perm('ldt_utils.view_project', proj.owner, proj)
        assign_perm('ldt_utils.change_project', proj.owner, proj)            
            
        if verbose:
            writer = show_progress(i, total, "Assign permissions to projects", 40, writer)
        
    for published_proj in list_model['Project'].objects.filter(state=2):
        assign_perm('ldt_utils.view_project', everyone, published_proj)
    
    if verbose:    
        writer = None
        total = list_model['User'].objects.count()
        
    for i, user in enumerate(list_model['User'].objects.all()):
        user.groups.add(everyone)
        if verbose:
            writer = show_progress(i, total, "Assign permissions to groups", 40, writer)         
          
        for group in user.groups.exclude(name=settings.PUBLIC_GROUP_NAME):
            for proj in list_model['Project'].objects.filter(owner=user):
                assign_perm('ldt_utils.view_project', group, proj)
            
        for content in list_model['Content'].objects.all():
            if user.has_perm('view_content', content):
                assign_perm('ldt_utils.view_media', user, content.media_obj)
    
                
    for admin in list_model['User'].objects.filter(is_superuser=True):
        for g in list_model['Group'].objects.all():
            admin.groups.add(g)
            