/*
 * Copyright 2015 Open mHealth
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.openmhealth.shim.fitbit.mapper;

import com.fasterxml.jackson.databind.JsonNode;
import org.openmhealth.schema.domain.omh.DataPoint;
import org.openmhealth.schema.domain.omh.DurationUnitValue;
import org.openmhealth.schema.domain.omh.SleepDuration1;
import org.openmhealth.schema.domain.omh.TimeInterval;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.Optional;

import static org.openmhealth.schema.domain.omh.DurationUnit.MINUTE;
import static org.openmhealth.shim.common.mapper.JsonNodeMappingSupport.*;


/**
 * A mapper that translates responses from the Fitbit Resource API <code>sleep/date</code> endpoint into {@link
 * SleepDuration1} data points.
 *
 * @author Chris Schaefbauer
 * @see <a href="https://dev.fitbit.com/docs/sleep/#get-sleep-logs">API documentation</a>
 */
public class FitbitSleepDurationDataPointMapper extends FitbitDataPointMapper<SleepDuration1> {

    @Override
    protected String getListNodeName() {
        return "sleep";
    }

    @Override
    protected Optional<DataPoint<SleepDuration1>> asDataPoint(JsonNode node) {

        DurationUnitValue unitValue = new DurationUnitValue(MINUTE, asRequiredDouble(node, "minutesAsleep"));
        SleepDuration1.Builder sleepDurationBuilder = new SleepDuration1.Builder(unitValue);

        Optional<LocalDateTime> localStartTime = asOptionalLocalDateTime(node, "startTime");

        if (localStartTime.isPresent()) {

            OffsetDateTime offsetStartDateTime = asOffsetDateTimeWithFakeUtcTimeZone(localStartTime.get());
            Optional<Double> timeInBed = asOptionalDouble(node, "timeInBed");

            if (timeInBed.isPresent()) {
                sleepDurationBuilder.setEffectiveTimeFrame(TimeInterval.ofStartDateTimeAndDuration(offsetStartDateTime,
                        new DurationUnitValue(MINUTE, timeInBed.get())));
            }
            else {
                // in this case, there is no "time in bed" value, however we still have a start time, so we can set
                // the data point to a single date time point
                sleepDurationBuilder.setEffectiveTimeFrame(offsetStartDateTime);
            }
        }

        SleepDuration1 measure = sleepDurationBuilder.build();

        Optional<Long> externalId = asOptionalLong(node, "logId");

        return Optional.of(newDataPoint(measure, externalId.orElse(null)));
    }
}

@@ -849,17 +849,17 @@
 Duration
-1
+2
 ;%0Aimport
@@ -911,40 +911,65 @@
 al;%0A
-%0A
 import 
-java.time.LocalDateTime;
+org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A
 %0Aimp
@@ -1026,16 +1026,56 @@
 ional;%0A%0A
+import static java.util.Optional.empty;%0A
 import s
@@ -1344,17 +1344,17 @@
 Duration
-1
+2
 %7D data p
@@ -1392,16 +1392,44 @@
 efbauer%0A
+ * @author Emerson Farrugia%0A
  * @see 
@@ -1576,16 +1576,28 @@
 s Fitbit
+SleepMeasure
 DataPoin
@@ -1621,14 +1621,123 @@
 tion
-1
+2
 %3E %7B%0A%0A
+    private static final Logger logger = LoggerFactory.getLogger(FitbitSleepDurationDataPointMapper.class);%0A%0A
     
@@ -1878,17 +1878,17 @@
 Duration
-1
+2
 %3E%3E asDat
@@ -1925,66 +1925,39 @@
    D
-urationUnitValue unitValue = new DurationUnitValue(MINUTE,
+ouble totalSleepTimeInMinutes =
  asR
@@ -1992,18 +1992,18 @@
 Asleep%22)
-)
 ;
+%0A
 %0A       
@@ -2007,90 +2007,152 @@
     
-SleepDuration1.Buil
+if (totalSleepTimeInMinutes == 0) %7B%0A            return empty();%0A        %7D%0A%0A        JsonNo
 de
-r
  sleep
-DurationBuil
+LevelsNo
 de
-r
  = 
-new SleepDuration1.Builder(unitValue
+asRequiredNode(node, %22levels.data%22
 );%0A%0A
@@ -2168,21 +2168,22 @@
 ptional%3C
-Local
+Offset
 DateTime
@@ -2188,66 +2188,66 @@
 me%3E 
-localStartTime = asOptionalLocalDateTime(node, %22startTime%22
+sleepOnsetDateTime = getSleepOnsetDateTime(sleepLevelsNode
 );%0A%0A
@@ -2258,26 +2258,31 @@
     if (
-localStart
+!sleepOnsetDate
 Time.isP
@@ -2297,196 +2297,192 @@
 ) %7B%0A
-%0A            OffsetDateTime offsetStartDateTime = asOffsetDateTimeWithFakeUtcTimeZone(localStartTime.get());%0A            Optional%3CDouble%3E timeInBed = asOptionalDouble(node, %22timeInBed%22
+            logger.warn(%0A                    %22The following Fitbit sleep log entry has positive 'minutesAsleep' but doesn't contain an asleep segment.%5Cn%7B%7D%22,%0A                    node
 );%0A
-%0A
     
@@ -2493,36 +2493,23 @@
     
-if (timeInBed.isPresent()) %7B
+return empty();
 %0A   
@@ -2509,32 +2509,35 @@
 ();%0A        
+%7D%0A%0A
         
 sleepDuratio
@@ -2528,477 +2528,439 @@
     
-sleepDurationBuilder.setEffectiveTimeFrame(TimeInterval.ofStartDateTimeAndDuration(offsetStartDateTime,%0A                        new DurationUnitValue(MINUTE, timeInBed.get())));%0A            %7D%0A            else %7B%0A                // in this case, there is no %22time in bed%22 value, however we still have a start time, so we can set%0A                // the data point to a single date time point%0A                sleepDurationBuilder.setEffectiveTimeFrame(offsetStartDateTime);
+OffsetDateTime arisingDateTime = getArisingDateTime(sleepLevelsNode).orElseThrow(IllegalStateException::new);%0A%0A        TimeInterval effectiveTimeInterval =%0A                TimeInterval.ofStartDateTimeAndEndDateTime(sleepOnsetDateTime.get(), arisingDateTime);%0A%0A        SleepDuration2 measure = new SleepDuration2.Builder(%0A                new DurationUnitValue(MINUTE, totalSleepTimeInMinutes),%0A                effectiveTimeInterval)
 %0A   
@@ -2972,74 +2972,12 @@
     
-%7D%0A
     
-    %7D%0A%0A        SleepDuration1 measure = sleepDurationBuilder
 .bui

Refactor Fitbit sleep duration mapper