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

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, created = Group.objects.get_or_create(name=settings.PUBLIC_GROUP_NAME)     
     
    if verbose:   
        i = 1
        total = list_model['Project'].objects.count()
        
    for proj in list_model['Project'].objects.all():
        
        if proj.state == 2:
            proj.publish()
        else:
            proj.unpublish()
            
        if verbose:
            show_progress(i, total, "Assign permissions to projects", 40, writer)
            i += 1
        
    for published_proj in list_model['Project'].objects.filter(state=2):
        assign('ldt_utils.view_project', everyone, published_proj)
    
    if verbose:    
        i = 1
        writer = None
        total = list_model['User'].objects.count()
        
    for user in list_model['User'].objects.all():
        everyone.user_set.add(user) 
        if verbose:
            show_progress(i, total, "Assign permissions to groups", 40, writer)
            i += 1           
          
        for group in user.groups.exclude(name=settings.PUBLIC_GROUP_NAME):
            for proj in list_model['Project'].objects.filter(owner=user):
                assign('ldt_utils.view_project', group, proj)
            
        for content in list_model['Content'].objects.all():
            if user.has_perm('view_content', content):
                assign('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():
            g.user_set.add(admin)