# This sucks.  Make it not suck.
import os, shutil, tempfile, hashlib

chunk_size = 1024*1024 # TODO: is this a good chunk size?

from pylons import config

"""
Notes:
# You can get a mime type like so:
from mimetypes import guess_type
guess_type(temp.filename)[0]
"""

def get_path(space, hash):
    return "/" + os.path.join( space, hash[:2], hash[2:] )


def save_file(space, fileobj, hash=None):
    """Saves the contents of fileobj to the given storage space.

    If a hash is not provided, the SHA-1 sum of the file will be computed and
    that will be used.  The ideal scenario here is to let the hash of the
    original file be computed automatically, then create thumbnails et al. with
    the same hash in a different space.

    Returns the hashsum.
    """
    dest_root = os.path.join( config['app_conf']['static_root'], space )

    # The incoming fileobj could be a tempfile that's already been unlinked --
    # and probably is, as it's coming from a Pylons upload object.  Thus we
    # have to copy the data rather than the file, and we may have to read the
    # file anyway to hash it, so do both at the same time.

    # Need a named temporary file to write to; it gets renamed once the hash is
    # computed
    temp_fd, temp_path = tempfile.mkstemp()
    temp_file = os.fdopen(temp_fd, "wb")

    sha1 = hashlib.sha1()
    while True:
        data = fileobj.read(chunk_size)
        if not data:
            break

        if not hash:
            sha1.update(data)
        temp_file.write(data)

    temp_file.close()
    if not hash:
        hash = sha1.hexdigest()

    # Git convention: first two characters are the directory
    dest_dir  = os.path.join(dest_root, hash[:2])
    dest_path = os.path.join(dest_dir,  hash[2:])

    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)
    print dest_path
    shutil.move(temp_path, dest_path)

    return hash
