"""
Management command to unregister students with masked email.
"""
import logging
from optparse import make_option

from django.core.management.base import BaseCommand

from biz.djangoapps.ga_invitation.models import (ContractRegister, UNREGISTER_INVITATION_CODE)
from student.models import CourseEnrollment

log = logging.getLogger(__name__)


class Command(BaseCommand):

    help = """
    Unregister a student of masked user.

    Example:
      python manage.py lms --settings=aws unregister_masked_user [--debug]
    """

    option_list = BaseCommand.option_list + (
        make_option('--debug',
                    default=False,
                    action='store_true',
                    help='Use debug log'),
    )

    def handle(self, *args, **options):
        debug = options.get('debug')
        if debug:
            stream = logging.StreamHandler(self.stdout)
            log.addHandler(stream)
            log.setLevel(logging.DEBUG)
        log.info(u"unregister_masked_user command start {}".format('(dry run)' if debug else ''))
        # find users who are masked, which don't have an @ in the email, and unenroll from courses
        registers = ContractRegister.objects.exclude(user__email__contains='@').exclude(
            status=UNREGISTER_INVITATION_CODE).order_by('user__username')

        # debug output for comparison with sql output
        if debug:
            log.debug(u"--------------debug target output (start)--------------")
            log.debug(u"{}\t{}".format('username', 'course_id'))
            for register in registers:
                for enrollment in CourseEnrollment.enrollments_for_user(register.user).order_by('course_id'):
                    log.debug(u"{}\t{}".format(register.user.username, enrollment.course_id))
            log.debug(u"--------------debug target output (finished)--------------")

        # do unregister and unenroll (dry run if debug mode)
        target_found = False
        for register in registers:
            target_found = True
            log.info(u"unregistering [start]... register.user.username:{}, register.user.email:{}".format(
                register.user.username, register.user.email))
            # will not really unregister when in debug mode, it is a dry run
            if not debug:
                register.status = UNREGISTER_INVITATION_CODE
                register.save()
            for enrollment in CourseEnrollment.enrollments_for_user(register.user).order_by('course_id'):
                log.info(u"unenrolling ... username:{}, course_id:{}".format(register.user.username,
                                                                             enrollment.course_id))
                # will not really unenroll when in debug mode, it is a dry run
                if not debug:
                    CourseEnrollment.unenroll(enrollment.user, enrollment.course_id)
            log.info(u"unregistering [finished]... register.user.username:{}, register.user.email:{} ".format(
                register.user.username, register.user.email))

        if not target_found:
            log.warn(u"unregister_masked_user command target not found.")

        log.info(u"unregister_masked_user command finished {}".format('(dry run)' if debug else ''))

@@ -164,16 +164,77 @@
 ommand%0A%0A
+from biz.djangoapps.ga_contract.models import ContractDetail%0A
 from biz
@@ -1372,16 +1372,89 @@
 ername')
+%0A        course_ids = %5Bd.course_id for d in ContractDetail.objects.all()%5D
 %0A%0A      
@@ -1511,32 +1511,70 @@
       if debug:%0A
+            register_user_set = set()%0A
             log.
@@ -1735,32 +1735,199 @@
 r in registers:%0A
+                if register.user in register_user_set:%0A                    continue%0A                else:%0A                    register_user_set.add(register.user)%0A    
                 
@@ -1989,32 +1989,94 @@
 (register.user).
+filter(%0A                            course_id__in=course_ids).
 order_by('course
@@ -2074,32 +2074,36 @@
 y('course_id'):%0A
+    
                 
@@ -2265,17 +2265,34 @@
 -----%22)%0A
-%0A
+        else:%0A    
         
@@ -2324,69 +2324,70 @@
 oll 
-(dry run if debug mode)%0A        target_found = False%0A
+if not debug%0A            register_user_set = set()%0A   
         
 for 
@@ -2374,32 +2374,33 @@
 et()%0A           
+ 
 for register in 
@@ -2426,28 +2426,164 @@
     
-target_found = True%0A
+    if(register.user in register_user_set):%0A                    continue%0A                else:%0A                    register_user_set.add(register.user)%0A    
     
@@ -2582,32 +2582,36 @@
                 
+    
 log.info(u%22unreg
@@ -2697,32 +2697,40 @@
                 
+        
 register.user.us
@@ -2767,107 +2767,8 @@
     
-        # will not really unregister when in debug mode, it is a dry run%0A            if not debug:%0A
     
@@ -2832,32 +2832,36 @@
                 
+  
+  
 register.save()%0A
@@ -2860,16 +2860,24 @@
 .save()%0A
+        
         
@@ -2951,16 +2951,78 @@
 r.user).
+filter(%0A                            course_id__in=course_ids).
 order_by
@@ -3028,32 +3028,40 @@
 y('course_id'):%0A
+        
                 
@@ -3222,16 +3222,24 @@
         
+        
 enrollme
@@ -3261,113 +3261,8 @@
     
-            # will not really unenroll when in debug mode, it is a dry run%0A                if not debug:%0A
     
@@ -3346,32 +3346,40 @@
 id)%0A            
+       
+ 
 log.info(u%22unreg
@@ -3469,32 +3469,40 @@
                 
+        
 register.user.us
@@ -3531,25 +3531,26 @@
 email))%0A
-%0A
+  
         
 if not t
@@ -3545,29 +3545,40 @@
     
+  
 if not 
-target_found:%0A
+register_user_set:%0A    
     

Fix bug for unregister_masked_user command (#2253) (#2267)