# vim:spell:spelllang=fr
# -*- encoding: utf-8 -*-

import os
import os.path
from datetime import timedelta, datetime
import logging
import logging.handlers
from optparse import make_option

from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils.timezone import now, localtime, utc, get_default_timezone


from ... import app_settings
from ... import models



class Command(BaseCommand):
    can_import_django_settings = True
    requires_model_validation = True
    help = 'Purge les vieilles demandes'

    option_list = BaseCommand.option_list + (
            make_option("--before", help='la date seuil au format YYYY-MM-DD'),
            make_option("--fake", action="store_true", help='ne rien supprimer, faire semblant'))

    def handle(self, *args, **options):
        logger = logging.getLogger('polynum.purge')
        fake = '[fake] ' if options.get('fake') else ''
        if str(options.get('verbosity')).strip() == '2':
            handler = logging.StreamHandler()
            handler.setLevel(logging.INFO)
            logger.addHandler(handler)
        if options.get('before') is not None:
            before = get_default_timezone().localize(
                    datetime.strptime(options.get('before').strip(), 
                                   '%Y-%m-%d'))
        else:
            lifetime = timedelta(
                    days=app_settings.MAXIMUM_DAYS_BEFORE_PURGE)
            before = now()-lifetime
            before = before.replace(hour=0, minute=0, second=0)
        logger.info('%sPurge des demandes antérieures à la date du %s',
                fake,
                before.strftime('%Y-%m-%d'))
        try:
            qs = models.Request.objects.filter(modification_date__lt=before)
            for request in qs:
                if not fake:
                    request.delete()
                logger.info('%s- suppression de la demande %s',
                        fake, request.request_number())
        except:
            logger.exception('%serreur lors de la purge de la base de'
                    ' donnée...', fake)
        upload_dir = os.path.join(settings.MEDIA_ROOT,
                models.Request._meta.get_field('uploadfile').upload_to)
        logger.info('%sPurge des fichiers uploadés dans %s...',
                fake,
                upload_dir)
        for root, dirs, files in os.walk(upload_dir):
            for name in files:
                path = os.path.join(root, name)
                creation_time = datetime.utcfromtimestamp(os.path.getctime(path)).replace(tzinfo=utc)
                if creation_time < before:
                    logger.info('%s- supression du fichier %s',
                            fake,
                            name)
                    if not fake:
                        os.unlink(path)






