# vim: fileencoding=utf8
from django.conf import settings
from addressbook.models import Card
import os.path
import amf, amf.django

def getCards(request):
    return Card.objects.all().order_by('firstName', 'lastName')

def saveCard(request, card):
    if card.id > 0:
        # update
        _save_portrait_data_if_exists(card)
        card.save()
    else:
        # new
        card.id = None
        _save_portrait_data_if_exists(card)
        card.save()

def _save_portrait_data_if_exists(card):
    data = card.portrait
    if data:
        if card.portraitUrl:
            filename = os.path.basename(card.portraitUrl)
        else:
            filename = _gen_filename()
        paths = amf.django.save_to_file(data, filename)
        card.portraitUrl = paths['url']

def _gen_filename():
    import string
    from random import choice
    return 'dj_' + ''.join([ choice(string.letters + string.digits) for i in range(23) ]) + '.png'

def deleteCard(request, id):
    card = Card.objects.get(id=id)
    if card:
        _delete_portrait_file_if_exists(card)
        card.delete()

def _delete_portrait_file_if_exists(card):
    if card.portraitUrl:
        filename = os.path.basename(card.portraitUrl)
        amf.django.delete_file(filename)

