const moment = require('moment-timezone')
const twitchAPI = require('./twitchAPI')
const Archive = require('./mongo').ArchivedVideoLengths
const _ = require('lodash')

async function update() {
  const { body } = await twitchAPI.getArchivesKraken()
  const { videos } = body
  const locked = await Archive.find({ locked: true })
  const lockedIds = locked.map((x) => x.videoId)
  const operations = []
  videos.forEach((video) => {
    if (lockedIds.includes(video.broadcast_id.toString())) return
    operations.push({
      updateOne: {
        filter: { videoId: video.broadcast_id },
        update: {
          videoId: video.broadcast_id,
          createdAt: video.created_at,
          length: video.length,
        },
        upsert: true,
      },
    })
  })
  if (operations.length === 0) return
  await Archive.bulkWrite(operations)
}

async function getHoursThisQuarter() {
  const startOfQuarter = moment
    .tz('America/Los_Angeles')
    .startOf('quarter')
    .subtract(1, 'month')
    .startOf('month')
  const endOfQuarter = moment
    .tz('America/Los_Angeles')
    .endOf('quarter')
    .subtract(1, 'month')
    .endOf('month')
  const startOfLastQuarter = moment
    .tz('America/Los_Angeles')
    .startOf('quarter')
    .subtract(1, 'quarter')
    .subtract(1, 'month')
    .startOf('month')
  const endOfLastQuarter = moment
    .tz('America/Los_Angeles')
    .endOf('quarter')
    .subtract(1, 'quarter')
    .subtract(1, 'month')
    .endOf('month')
  return {
    thisQuarter: await getHours(startOfQuarter, endOfQuarter),
    lastQuarter: await getHours(startOfLastQuarter, endOfLastQuarter),
  }
}

async function getHours(start, end) {
  const videos = await Archive.find({
    createdAt: { $gte: start, $lte: end },
  })
  const sum = videos.reduce((prev, next) => {
    return prev + next.length
  }, 0)
  const duration = moment.duration(sum, 'seconds')
  return Math.round(duration.asHours())
}

module.exports = () => {
  // Process videos every 20 minutes
  update().catch()
  setInterval(update, 1000 * 60 * 20)
  return {
    getHoursThisQuarter,
  }
}

@@ -973,34 +973,29 @@
 ')%0A    .
-subtract(1
+add(2
 , 'month
 ')%0A    .
@@ -978,32 +978,33 @@
   .add(2, 'month
+s
 ')%0A    .startOf(
@@ -1070,35 +1070,37 @@
 _Angeles')%0A    .
-end
+start
 Of('quarter')%0A  
@@ -1102,34 +1102,29 @@
 ')%0A    .
-subtract(1
+add(4
 , 'month
 ')%0A    .
@@ -1107,32 +1107,33 @@
   .add(4, 'month
+s
 ')%0A    .endOf('m
@@ -1210,32 +1210,8 @@
 s')%0A
-    .startOf('quarter')%0A
     
@@ -1240,33 +1240,52 @@
 )%0A    .s
-ubtract(1
+tartOf('quarter')%0A    .add(2
 , 'month
 ')%0A    .
@@ -1268,32 +1268,33 @@
   .add(2, 'month
+s
 ')%0A    .startOf(
@@ -1371,30 +1371,8 @@
 s')%0A
-    .endOf('quarter')%0A
     
@@ -1405,25 +1405,44 @@
   .s
-ubtract(1
+tartOf('quarter')%0A    .add(4
 , 'month
 ')%0A 
@@ -1433,24 +1433,25 @@
 dd(4, 'month
+s
 ')%0A    .endO

refactor quarters calc