import shutil
import os
import os.path
import datetime as dt

from django.core.management.base import BaseCommand
import django.contrib.auth.models as auth_models
from django.db import transaction
from django.conf import settings
from django.core import serializers

from ... import models
from ... import timestamp
import django_journal

class Command(BaseCommand):
    args = '<directory>'
    help = 'Save logs, and user list'

    def save_documents(self):
        documents = models.Document.objects.filter(date__lt=self.before)
        for document in documents:
            print ' - Archiving document ', document.id
            doc_path = os.path.join(self.doc_path, str(document.id))
            os.mkdir(doc_path)
            json_path = os.path.join(doc_path, 'document.json')
            with file(json_path, 'w') as document_json:
                document_json.write(
                        serializers.serialize('json', [document],
                            indent=2, use_natural_keys=True))
            for attached_file in document.attached_files.all():
                file_path = os.path.join(doc_path, os.path.basename(attached_file.content.name))
                with file(file_path, 'w') as data_file:
                    data_file.write(attached_file.content.read())
                attached_file_path = os.path.join(doc_path,
                        'attached_file_%s.json' % attached_file.id)
                with file(attached_file_path, 'w') as json_file:
                    json_file.write(serializers.serialize('json',
                        [attached_file], indent=2))
        # documents.delete()

    def save_journal(self):
        journals = django_journal.Journal.objects \
                .filter(time__lt=self.before) \
                .order_by('time') \
                .select_related('tag', 'template') \
                .prefetch_related('objectdata_set__content_type',
                          'stringdata_set', 'objectdata_set__tag',
                          'stringdata_set__tag', 'objectdata_set__content_object')
        journal_path = os.path.join(self.path, 'journal.txt')
        with file(journal_path, 'w') as journal_file:
            for journal in journals:
                print >> journal_file, journal.time, unicode(journal).encode('utf-8').replace('\n', '\n  ')
        print ' - Archived %d lines of the journal' % journals.count()
        # journals.delete()

    @transaction.commit_on_success
    def handle(self, *args, **options):
        self.directory = args[0]
        self.days = int(args[1])
        self.before = dt.datetime.utcnow() - dt.timedelta(days=self.days)
        print 'Archive journal and documents older than', self.before, ':'
        self.path = os.path.join(self.directory, dt.datetime.now().isoformat())
        self.doc_path = os.path.join(self.path, 'doc')
        os.mkdir(self.path)
        os.mkdir(self.doc_path)
        try:
            self.save_documents()
            self.save_journal()
        except:
            shutil.rmtree(self.path)
            raise
