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
import pdb

def set_default_permissions(verbose=False, is_migration=False, orm=None):
    
    list_model = {'Project': Project,
                  'Content': Content,
                  'User': User,
                  'Group': Group
                  }
    
    if is_migration:
        list_model = {'User': orm['auth.user'],
                      'Group': orm['auth.group'],
                      'Project': orm.Project,
                      'Content': orm.Content
                      }
    
    everyone, created = Group.objects.get_or_create(name=settings.PUBLIC_GROUP_NAME)     
     
    if verbose:   
        print "Set project permissions..."
        
    for proj in list_model['Project'].objects.all():
        assign('ldt_utils.change_project', proj.owner, proj)
        assign('ldt_utils.view_project', proj.owner, proj)
        
    for published_proj in list_model['Project'].objects.filter(state=2):
        assign('ldt_utils.view_project', everyone, published_proj)
    
    if verbose:    
        print "Set group permissions...[This may take a while]"
        
    for user in list_model['User'].objects.all():
        everyone.user_set.add(user) 
          
        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('view_media', user, content.media_obj)
    
    if verbose:
        print "Set content permissions..."
    for c in list_model['Content'].objects.all():
        c.is_public = True
            
    for admin in list_model['User'].objects.filter(is_superuser=True):
        for g in list_model['Group'].objects.all():
            g.user_set.add(admin)