'use strict'
module.exports = ficInflate

const Bluebird = require('bluebird')
const qw = require('qw')

const progress = use('progress')

// Take a fic and fetch all its chapters and ensure its per-chapter metadata
// is fully complete.

function ficInflate (fic, fetch, tracker) {
  if (!tracker) tracker = progress.tracker
  return fic.then(fic => {
    const fics = [fic].concat(fic.fics)
    const completion = new Map()
    for (let fic of fics) {
      completion.set(fic, tracker.newItem(fic.title, fic.chapters.length))
    }
    return Bluebird.map(fics, fic => {
      const tracker = completion.get(fic)
      process.emit('debug', 'Inflating', fic.title, 'chapters:', fic.chapters.length)
      let words = 0
      return Bluebird.map(fic.chapters, chapterInfo => {
        const chapterContent = chapterInfo.getContent(fetch)
        return progress.completeWorkWhenResolved(chapterContent, tracker).then(chapter => {
          process.emit('debug', `Got content for #${chapterInfo.order}: ${chapterInfo.name}`)
          progress.show(fic.title, `${chapterInfo.name}`)
          chapterInfo.words = chapter.words
          words += chapter.words
          if (chapterInfo.link == null) chapterInfo.link = chapter.chapterLink
          for (let prop of qw`name author authorUrl created modified headings`) {
            if (chapterInfo[prop] == null) chapterInfo[prop] = chapter[prop]
          }
          if (chapterInfo.author === fic.author || chapterInfo.authorUrl === fic.authorUrl) {
            chapterInfo.author = null
            chapterInfo.authorUrl = null
          }
        }).catch(err => {
          chapterInfo.error = err
          process.emit('error', err.message)
        })
      }).finally(() => {
        if (!fic.words) fic.words = words
        tracker.finish()
      })
    })
  }).thenReturn(fic)
}

@@ -1768,24 +1768,445 @@
 rds = words%0A
+        const firstChapter = fic.chapters%5B0%5D%0A        const lastChapter = fic.chapters%5Bfic.chapters.length - 1%5D%0A        if (firstChapter.created == null && firstChapter.modified == null && fic.created != null) %7B%0A          firstChapter.created = fic.created%0A        %7D%0A        if (lastChapter.created == null && lastChapter.modified == null && fic.modified != null) %7B%0A          lastChapter.modified = fic.modified%0A        %7D%0A
         trac

Update first/last chapter create/mod times from fic if missing