'''
set just created medias and contents public
'''
import csv

from django.conf import settings
from django.core.management.base import BaseCommand
from django.contrib.auth.models import Group

from ldt.security.cache import cached_assign
from ldt.ldt_utils.models import Content, Media


class Command(BaseCommand):
    '''
    command
    '''

    def add_arguments(self, parser):
        '''
        add arguments
        '''
        parser.add_argument('-p',
                            nargs='+',
                            dest='pathes',
                            default=None)

    def handle(self, *args, **options):
        '''
        handle command
        '''
        sources = []
        for path in options['pathes']:
            self.stdout.write(path)
            try:
                csvfile = open(path, 'r')
            except IOError:
                self.stdout.write('file can\'t be opened')
                continue
            files = csv.reader(csvfile)
            sources += list([content[0] for content in files])
            csvfile.close()
        everyone = Group.objects.get(name=settings.PUBLIC_GROUP_NAME)
        for source in sources:
            media = Media.objects.get(src=source)
            content = Content.objects.get(media_obj_id=media.id)
            content.is_public = True
            content.save()
            cached_assign('view_content', everyone, content)
            cached_assign('view_media', everyone, media)

    