 # create a FormData object with photo.file and photo.thumb
 # save the model with these files
 upload = (photo, next) ->
-
     formdata = new FormData()
     formdata.append 'raw', photo.file
     formdata.append 'thumb', photo.thumb, "thumb_#{photo.file.name}"


    Backbone.sync 'create', photo,
      contentType: false # Prevent $.ajax from being smart
      success: -> next()
      data: formdata


# delete all object attached to the photo
# the photo is now backed by the server
clearTemp = (photo, next) ->
    delete photo.file
    delete photo.img
    delete photo.file_du
    delete photo.thumb
    delete photo.thumb_du
    next()


# async waterfall of all the above
operation = (task , callback) ->
    {photo, file} = task
    photo.file = file
    async.waterfall [
        (cb) -> readFile photo         , cb
        (cb) -> makeThumbDataURI photo , cb
        (cb) -> makeThumbBlob photo    , cb
        (cb) -> upload photo           , cb
        (cb) -> clearTemp Photo        , cb
    ], callback

# number of pictures being processed at any time
concurrency = 3

queue = async.queue operation, concurrency

module.exports.process = (file, photo) ->
    queue.push
        file: file
        photo: photo
    , ->

# width and height of generated thumbs
MAX_WIDTH = MAX_HEIGHT = 100
TYPEREGEX = ///image/.*///

# read the file from photo.file using a FileReader
# create photo.img : an Image

readFile = (photo, next) ->
    if photo.file.size > 6*1024*1024
        return next('too big')

    if not photo.file.type.match TYPEREGEX
        return next('not an image')

    reader = new FileReader()
    photo.img = new Image()
    reader.readAsDataURL photo.file
    reader.onloadend = =>
        photo.img.src = reader.result
        photo.img.onload = ->
            next()
