from django.core.management.base import BaseCommand
from rldjango.apps.imadj.models import Tag
from django.db import connection

class Command(BaseCommand):
    """
    Mamangment command used to remove unused imadj tags.
    """
    help = "Remove unused imadj tags."


    def handle(self, *args, **options):
        """
        For all section call generate_iamges
        """

        cursor = connection.cursor()
        
        cursor.execute("SELECT imadj_tag.id FROM imadj_tag LEFT OUTER JOIN imadj_image_tags \
                       ON imadj_tag.id=tag_id WHERE tag_id IS NULL")
        unused_tags = cursor.fetchall()
        unused_tags = [x[0] for x in unused_tags]
        
        print 'Removing %d unused tags' % len(unused_tags)
        
        for tag in unused_tags:
            tag = Tag.objects.get(id=tag).delete()
        
