import { Promise } from 'bluebird'
import fg from 'fast-glob'
import fs from 'fs'
import path from 'path'
import { Executor, PipelineStep, PipelineStepSettings } from '../pipeline'

export function run (executor: Executor) {
  return Promise
    .resolve()
    .then(() => fg([executor.getInputPath('/**/*.meta-input.json')]))
    .then(paths => Promise.mapSeries(paths, (metaInputPath) => {
      const filePath = metaInputPath.replace('.meta-input.json', '')
      let metaInput
      try {
        metaInput = JSON.parse(fs.readFileSync(metaInputPath).toString())
      } catch (error) {
        throw new Error('Could not parse (bad JSON): ' + metaInputPath)
      }
      return {
        path: path.relative(executor.getInputPath(), filePath),
        metaInput: metaInput,
        data: fs.readFileSync(filePath)
      }
    }))
    .then((files) => Promise.mapSeries(files, (f) => {
      return executor.toOutput({
        path: f.path,
        data: f.data,
        title: f.metaInput.title,
        description: f.metaInput.description,
        labels: f.metaInput.labels
      })
    }))
}

export function step (settings?: PipelineStepSettings): PipelineStep {
  return new PipelineStep(run, settings)
}
