import os.path
import json
import datetime

from app_settings import PFWB_GED_DIRECTORY
from ..docbow.models import AttachedFile
import models

def push_document(signal, sender, instance, **kwargs):
    attached_file = instance
    document = attached_file.document
    if not PFWB_GED_DIRECTORY:
        return
    try:
        plone_file_type = document.filetype.plonefiletype
    except models.PloneFileType.DoesNotExist:
        return
    tpl = '{sender.first_name} {sender.last_name} ({sender.username})'
    sender = tpl.format(sender=document.sender)
    metadata = {
            'document_id': document.id,
            'plone_portal_type': plone_file_type.plone_portal_type,
            'title': unicode(document.filetype),
            'description': document.comment,
            'reception_date': document.date.isoformat().split('.')[0],
            'sender': sender,
    }
    if attached_file.kind:
        metadata['kind'] = attached_file.kind.name
    name = os.path.basename(attached_file.name)
    name = '%s-%s-%s' % (document.id, datetime.datetime.now().isoformat(), name)
    json_name = name + '.json'
    path = os.path.join(PFWB_GED_DIRECTORY, name)
    path_json = os.path.join(PFWB_GED_DIRECTORY, json_name)
    with open(path, 'w') as f:
        f.write(attached_file.content.read())
    with open(path_json, 'w') as f:
        f.write(json.dumps(metadata))

from django.db.models import signals

signals.post_save.connect(push_document, sender=AttachedFile)
