 path = require 'path'
+fs = require 'fs'
 
 _ = require 'underscore'
 Q = require 'q'

    src: mkPath root, getOriginal(picture).src
    dst: mkPath root, dstPathOnServer

  makeDirectories(path.dirname(resizeOpts.dst)).then ->
    resizeImage(resizeOpts).spread (resized) ->
      albumUpdateSemaphore.push ->
        getAlbum(path: albumPath).then (album) ->
          picture = _.find album.pictures, (pic) -> pic.path == picture.path
          picture.media.push
            width: parseInt resized.width
            height: parseInt resized.height
            src: dstPathOnServer
          picture.media = _.sortBy picture.media, (medium) -> medium.width
          saveAlbum(album)
        .then ->
          process.stdout.write '.' unless quiet
    .fail ->
      console.warn '\nFailed to create thumbnail:', resizeOpts.src

createPreviews = (opts) ->
  {albums, sizes, concurrency, root, output, quiet} = opts

  albums.forEach (album) ->
    album.pictures.forEach (picture) ->
      sizes.forEach (size) ->
        do (album, picture, size) ->
          sem.push ->
            createPreview
              albumPath: album.path
              picture: picture
              size: size
              root: root
              output: output
              quiet: quiet
          .done()

  sem.finished

