def delete(request,offset):
  if request.method == 'POST':
    
    user = User.objects.get(pk=int(offset))
    profile = UserProfile.objects.get(profile=int(offset))
    
    profile.delete()
    user.delete()
    
    system = request.session['system']
    
    #TO-DO pegar usarios pelo ID do sistema
    users = User.objects.filter(system=system)
    
    return render_to_response("accounts/templates/delete_finish.html",locals(),context_instance=RequestContext(request))
    
  else:
    user = User.objects.get(pk=int(offset))
    profile = UserProfile.objects.get(profile=int(offset))
    
    system = request.session['system']
    try:
        s = System.objects.get(users__id=user.id)
    except:
        s = System.objects.get(administrator__id = user.id)
        
    if isChild(s.id,[system,findChild(system)]): 
      return render_to_response("accounts/templates/delete.html",locals(),context_instance=RequestContext(request))
      
    else:
      return HttpResponseForbidden(u'Você não tem permissão para deletar este usuário.')      
 def inner_decorator(request,*args, **kwargs):
     system = args[0]
     childs = findChild(request.session["system"])
     if isChild(int(system),childs):
         return func(request, *args, **kwargs)
     else:
         return HttpResponseForbidden(u"Você não tem permissão para alterar esse sistema.")        
def edit(request,offset):
  
  user = User.objects.get(pk=int(offset))
  profile = UserProfile.objects.get(profile=int(offset))
  first_login = profile.is_first_login
  if request.method == 'POST':
    request.session["dont_check_first_login"] = True
    form = UserCompleteForm(request.POST,instance= user,profile=profile)
    form_user = UserForm(request.POST, instance = user)
    form_profile = UserProfileForm(request.POST, instance = profile)
    
    
    if form_user.is_valid() and form_profile.is_valid():
        new_user = form_user.save(commit=False)
        new_user.set_password(new_user.password)
        new_user.save()
        
        try:
            alert = request.POST["alert"]
        except:
            alert = None
            
        try:
          command = request.POST["command"]
        except:
          command = None

        try:
          adm = request.POST['Administrador']
        except:
          adm = None

        
        if adm is not None:
          user.groups.add(1)
          
        elif alert is not None and command is not None:
          user.groups.add(2)
          user.groups.add(3)
          
        elif command is not None:
          user.groups.add(3)
          
        elif alert is not None:
          user.groups.add(2)
        
        new_profile = form_profile.save()
        if (first_login == False):
            return HttpResponseRedirect ("/accounts/edit/finish")
        else:
            profile.is_first_login == False
            profile.save()
            return HttpResponseRedirect ("/accounts/edit/finish_firstlogin")

    return render_to_response("accounts/templates/edit.html",locals(),context_instance=RequestContext(request))
    
  else:
    request.session["dont_check_first_login"] = False
    system = request.session['system']
    users = User.objects.filter(system=system)
    profile = UserProfile.objects.get(profile=user)
    
    try:
        s = System.objects.get(users__id=user.id)
    except:
        s = System.objects.get(administrator__id = user.id)
    if isChild(s.id,[system,findChild(system)]):

        form = UserCompleteForm(instance = user,profile = profile)
      
        # ROOOTS BLOODY ROOTS
        if profile.is_first_login == False:
            form.fields["Administrador"] = forms.CharField(widget=forms.CheckboxInput(),help_text="Marque a caixa para atribuir privilégios administrativos ao usuário")
      
        else:
            title1 = "Primeiro acesso"
            
            title2 = "Para sua segurança solicitamos que mude sua senha antes de acessar o sistema."
            
        form.initial = dict( form.initial.items() + profile.__dict__.items())
        form.initial["password"] = ""
        return render_to_response("accounts/templates/edit.html",locals(),context_instance=RequestContext(request))
      
    else:
      return HttpResponseForbidden(u'Você não tem permissão para editar este usuário.')