from optparse import make_option

from django.core.management.base import (
    BaseCommand,
    CommandError,
)

from apps.api.models import (
    Group,
)


class Command(BaseCommand):
    help = "Merge selected gorups"
    option_list = BaseCommand.option_list + (
        make_option(
            "-o",
            "--old",
            dest="old",
            help="specify old pk",
        ),
    )
    option_list = option_list + (
        make_option(
            "-n",
            "--new",
            dest="new",
            help="specify new pk",
        ),
    )

    def handle(self, *args, **options):
        # make sure file option is present
        if options['old'] is None:
            raise CommandError("Option `--old=...` must be specified.")

        if options['new'] is None:
            raise CommandError("Option `--new=...` must be specified.")

        # make sure both groups exist
        try:
            new_group = Group.objects.get(pk=options['new'])
        except Group.DoesNotExist:
            raise CommandError("Target group does not exist.")
        try:
            old_group = Group.objects.get(pk=options['old'])
        except Group.DoesNotExist:
            raise CommandError("Subject group does not exist.")

        # perform de-dup
        try:
            contestants = old_group.contestants.all()
            for contestant in contestants:
                contestant.group = new_group
                contestant.save()
        except Exception as e:
            raise CommandError("Error moving contestants: {0}".format(e))

        # remove redundant group
        try:
            old_group.delete()
        except Exception as e:
            raise CommandError("Error deleted old group: {0}".format(e))

        return "Merged {0} into {1}".format(old_group, new_group)

@@ -27,16 +27,54 @@
 option%0A%0A
+from django.db import IntegrityError%0A%0A
 from dja
@@ -1322,31 +1322,66 @@
         
-try:%0A  
+contestants = old_group.contestants.all()%0A
         
   contes
@@ -1364,33 +1364,38 @@
 s.all()%0A        
- 
+if not
  contestants = o
@@ -1394,43 +1394,86 @@
 ants
- = old_group.
+:%0A            old_group.delete()%0A            return 'No 
 contes
-t
 ants
-.all()%0A    
+ to move.'%0A%0A
     
@@ -1511,36 +1511,32 @@
 ts:%0A            
-  
-  
 contestant.group
@@ -1547,24 +1547,38 @@
 ew_group%0A   
+         try:%0A
             
@@ -1570,32 +1570,35 @@
 y:%0A             
+   
 contestant.save(
@@ -1607,39 +1607,47 @@
         
+    
 except 
-Exception as e:%0A
+IntegrityError:%0A    
         
@@ -1673,23 +1673,31 @@
 ror(
-%22Error moving c
+%0A                    %22C
 onte
@@ -1705,25 +1705,84 @@
 tant
-s:
  %7B0%7D
-%22.format(e)
+ already exists.  Merge manually%22.format(contestant.id)%0A                
 )%0A%0A 

Check for existing Contestants