         return callback err if err
         processData stepsMeasures
 
+
+
+# Fetch sleep data from another url (it looks it's required by the withings
+# API).
+fetchAndSaveSleepMeasures = (options, callback) ->
+    opts =
+        strictSSL: false
+        form:
+            sessionid: options.sessionid
+            userid: options.userid
+            subcategory: 37
+            startdateymd: '2013-12-24'
+            enddateymd: moment().format 'YYYY-MM-DD'
+            appname: 'my2'
+            appliver: '36871d49'
+            apppfm: 'web'
+            action: 'getbyuserid'
+
+    log.info 'Fetching sleep data...'
+    request.post activityUrl, opts, (err, res, body) ->
+        return callback err if err
+        log.info 'Fetching sleep data done.'
+        measures = JSON.parse body
+        saveSleepMeasures measures.body.series, callback
+
+
+# Save sleep measures if they are not already recorded.
+saveSleepMeasures = (measures, callback) ->
+    sleepsMeasures = []
+    for measure in measures
+        sleepsMeasures.push new Sleep
+            vendor: 'Withings'
+            date: moment measure.date, 'YYYY-MM-DD'
+            awakeDuration: measure.data.wakeupduration
+            lightSleepDuration: measure.data.lightsleepduration
+            deepSleepDuration: measure.data.deepsleepduration
+            awakeTime: measure.data.wakeupcount
+            sleepDuration: (
+                measure.data.lightsleepduration + \
+                measure.data.deepsleepduration
+            )
+    log.info "#{measures.length} found"
+
+    Sleep.all (err, sleeps) ->
+        return callback err if err
+
+        sleepMap = {}
+        for sleep in sleeps
+            date = moment(sleep.date).format 'YYYY-MM-DD'
+            sleepMap[date] = true
+
+        sleepsToSave = sleepsMeasures.filter (measure) ->
+            date = moment(measure.date).format 'YYYY-MM-DD'
+            return not sleepMap[date]?
+
+        log.info "Saving sleeps..."
+        async.eachSeries sleepsToSave, (sleep, next) ->
+            Sleep.create sleep, next
+        , (err) ->
+            log.info "#{sleepsToSave.length} new sleep measures saved."
+            callback()
+

    vendor: {type: String, default: 'Withings'}

Steps = require '../models/steps'

Weight.all = (callback) ->
    Weight.request 'byDate', callback


        end = Math.ceil((new Date).getTime() / 1000)
        start = moment()
        start = start.year 2008
        start = start.month 0
        start = start.date 1
        start = Math.ceil(start.valueOf() / 1000)

        @fetchData email, password, start, end, (err) ->
            log.info 'import finished'
            callback err


    # Fetch data from withings website and save them as Cozy objects
