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

from optparse import make_option
import datetime

from django.core.management.base import BaseCommand
from django.conf import settings
from django.db import transaction

import django_journal

from appli_project.appli_socle import models, utils, settings as params

class Command(BaseCommand):
    '''
       Depublie automatiquement les annonces trop vieilles
    '''
    can_import_django_settings = True
    output_transaction = True
    requires_model_validation = True
    args = ''
    help = 'Depublie automatiquement les annonces trop vieilles'

    option_list = BaseCommand.option_list + (
                make_option("-n", "--fake", action="store_true"),
                make_option("-a", "--verbose", action="store_true"),
                make_option("--host"),
           )

    def slice(self, slicable, length):
        i = 0
        while True:
            l = slicable[i:i+length]
            yield l
            if len(l) < length:
                break
            i += length

    def desactivation_profil_offre(self, *args, **options):
        parametres = params.Parametres()
        aujourdhui = datetime.date.today() 
        seuil = aujourdhui - datetime.timedelta(
                days=parametres.duree_inactivite_profil_offre)
        qs = models.ProfilOffre.objects.filter(last_login__lte=seuil, is_active=True)
        if not options['fake']:
            qs.update(is_active=False)
            for profil in qs:
                django_journal.record('desactivation-compte', 
                    u'désactivation profil offre car dernière connection le {last_login}',
                    last_login=profil.last_login,
                    user=profil)
        if options['verbose'] and qs.exists():
            print 'Désactivation profils offre (seuil %s)' % seuil
            for profil in qs:
                print ' - Désactivation', unicode(profil).encode('utf-8')

    def desactivation_annonces(self, *args, **options):
        parametres = params.Parametres()
        aujourdhui = datetime.date.today()
        seuil = aujourdhui - datetime.timedelta(
                days=parametres.duree_maximum_de_publication)
        annonces = models.Annonce.objects \
                .filter(etat_validation='publiee',
                        derniere_validation__lte=seuil,
                        proprietaire__sans_validation=False) \
                .select_related('proprietaire') \
                .order_by('derniere_validation')
        if not options['fake']:
            for annonce in annonces:
                with transaction.commit_on_success():
                    try:
                        utils.mail_avec_modele_par_defaut(
                                'Depublication automatique',
                                { 'annonce': annonce, 'host': options['host'],
                                    'duree': parametres.duree_maximum_de_publication },
                                settings.VALIDATION_FROM,
                                annonce.proprietaire.email)
                    except:
                        django_journal.record('error',
                                u'impossible d\'envoyer un mail à {email} pour la dépublication automatique de son annonce',
                                email=annonce.proprietaire.email,
                                user=annonce.proprietaire)
                    annonce.etat_validation = 'valide'
                    annonce.save()
                    django_journal.record('depublie-annonce',
                            u'désactivation automatique annonce {annonce} publiée le {date_publication}',
                            annonce=annonce, user=annonce.proprietaire,
                            date_publication=max(annonce.derniere_validation, annonce.derniere_publication))
        if options['verbose'] and annonces.exists():
            print 'Dépublications des annonces (seuil %s)' % seuil
            for annonce in annonces:
                print ' - depublie', annonce.id, 'de', unicode(annonce.proprietaire).encode('utf-8')

    @transaction.commit_on_success
    def handle(self, *args, **options):
        self.desactivation_annonces(*args, **options)
        self.desactivation_profil_offre(*args, **options)
