import os.path
import json
import datetime

from django.db.models import signals
from django.utils.encoding import force_text

from ..docbow.models import AttachedFile
from . import app_settings, models


def push_document(signal, sender, instance, **kwargs):
    '''post-save signal handler, to push new documents inside the GED directory'''
    attached_file = instance
    document = attached_file.document
    if not app_settings.PFWB_GED_DIRECTORY:
        return
    try:
        plone_file_type = document.filetype.plonefiletype
    except models.PloneFileType.DoesNotExist:
        return
    tpl = u'{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': force_text(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(app_settings.PFWB_GED_DIRECTORY, name)
    path_json = os.path.join(app_settings.PFWB_GED_DIRECTORY, json_name)
    with open(path, 'wb') as f:
        f.write(attached_file.content.read())
    with open(path_json, 'w') as f:
        f.write(json.dumps(metadata))


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