import moment from "moment"

export const BETWEEN = "0"
export const BEFORE = "1"
export const AFTER = "2"
export const ON = "3"
export const LAST_DAY = -1 * 1000 * 60 * 60 * 24
export const LAST_WEEK = LAST_DAY * 7
export const LAST_MONTH = LAST_DAY * 30

export const RANGE_TYPE_LABELS = {
  [BETWEEN]: "Between",
  [BEFORE]: "Before",
  [AFTER]: "After",
  [ON]: "On",
  [LAST_DAY]: "Last 24 hours",
  [LAST_WEEK]: "Last 7 days",
  [LAST_MONTH]: "Last 30 days"
}

export function dateRangeStartKey(queryKey) {
  return queryKey ? queryKey + "Start" : "start"
}

export function dateRangeEndKey(queryKey) {
  return queryKey ? queryKey + "End" : "end"
}

export function dateToQuery(queryKey, value) {
  let startKey = dateRangeStartKey(queryKey)
  let endKey = dateRangeEndKey(queryKey)

  if (value.relative === BETWEEN) {
    // Between start and end date
    return {
      [startKey]: moment(value.start).startOf("day"),
      [endKey]: moment(value.end).endOf("day")
    }
  } else if (value.relative === BEFORE) {
    // Before end date
    return {
      [endKey]: moment(value.end).endOf("day")
    }
  } else if (value.relative === AFTER) {
    // After start date
    return {
      [startKey]: moment(value.start).startOf("day")
    }
  } else if (value.relative === ON) {
    // On given date
    return {
      [startKey]: moment(value.start).startOf("day"),
      [endKey]: moment(value.start).endOf("day")
    }
  } else {
    // LAST_DAY, LAST_WEEK, LAST_MONTH => Time relative to now, up till now
    return {
      [startKey]: parseInt(value.relative)
    }
  }
}

@@ -699,18 +699,20 @@
 ue) %7B%0A  
-le
+cons
 t startK
@@ -750,10 +750,12 @@
 )%0A  
-le
+cons
 t en
@@ -786,16 +786,220 @@
 ueryKey)
+%0A  const startDateStart = value.start && moment(null).startOf(%22day%22)%0A  const startDateEnd = value.start && moment(value.start).endOf(%22day%22)%0A  const endDateEnd = value.end && moment(value.end).endOf(%22day%22)
 %0A%0A  if (
@@ -1097,90 +1097,50 @@
 y%5D: 
-moment(value.start).startOf(%22day%22),%0A      %5BendKey%5D: moment(value.end).endOf(%22day%22)
+startDateStart,%0A      %5BendKey%5D: endDateEnd
 %0A   
@@ -1240,38 +1240,18 @@
 y%5D: 
-moment(value.end).endOf(%22day%22)
+endDateEnd
 %0A   
@@ -1353,42 +1353,22 @@
 y%5D: 
-moment(value.start).startOf(%22day%22)
+startDateStart
 %0A   
@@ -1464,92 +1464,52 @@
 y%5D: 
-moment(value.start).startOf(%22day%22),%0A      %5BendKey%5D: moment(value.start).endOf(%22day%22)
+startDateStart,%0A      %5BendKey%5D: startDateEnd
 %0A   

Fix endless retrieve loop when searching for invalid dates