# -*- coding: utf-8 -*-


import uuid
import os
from settings import UPLOAD_ROOT

from upload.models import Pic
# from pprint import pprint


def _make_directory(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)


def picSave(f, username="-"):

    pic = Pic()
    pic.path = fileSave(f, username)
    pic.save()
    return pic


def fileSave(f, username="-"):
    '''
        f  = request.FILES[key]
        username (string)
    '''
    directory = os.path.join(UPLOAD_ROOT, username)
    _make_directory(directory)

    filename = "%s.%s" % (uuid.uuid1(), f.name.split('.')[1])
    destPath = os.path.join(directory, filename)

    with open(destPath, 'wb+') as dest:
        for chunk in f.chunks():
            dest.write(chunk)

    return os.path.join(username, filename)
