import fs from 'fs'
import { HttpError } from 'flaska'
import formidable from 'formidable'
import config from '../config.mjs'

let lastDateString = ''
let incrementor = 1

function getPrefix() {
  const date = new Date()
  let prefix = ''

  // Generate 'YYYYMMDD_HHMMSS_' prefix
  prefix = date
    .toISOString()
    .replace(/-/g, '')
    .replace('T', '_')
    .replace(/:/g, '')
    .replace(/\..+/, '_')

  // Append xx_ if same date is hit multiple times
  if (prefix === lastDateString) {
    prefix += incrementor.toString().padStart('2', '0') + '_'
    incrementor++
  } else {
    lastDateString = prefix
    incrementor = 1
  }

  return prefix
}

export function uploadFile(ctx, siteName, noprefix = false) {
  return new Promise((res, rej) => {

    let prefix = ''

    var form = new formidable.IncomingForm()
    form.uploadDir = `${config.get('uploadFolder')}/${siteName}`
    form.maxFileSize = config.get('fileSize')

    let siteSize = config.get(`sites:${siteName}:fileSize`)

    if (siteSize && typeof(siteSize) === 'number') {
      form.maxFileSize = siteSize
    }

    form.parse(ctx.req, function(err, fields, files) {
      if (err) return rej(err)
      if (!files || !files.file) return rej(new HttpError(422, 'File in body was missing'))
      let file = files.file
      let filename = file.name.replace(/ /g, '_')
                              .replace(/&/g, 'and')
                              .replace(/'/g, '')
                              .replace(/"/g, '')
                              .replace(/\?/g, '')

      Object.keys(fields).forEach(function(key) {
        try {
          fields[key] = JSON.parse(fields[key])
        } catch { }
      })
      ctx.req.body = fields

      if (!noprefix || fs.existsSync(`${config.get('uploadFolder')}/${siteName}/${prefix}${filename}`)) {
        prefix = getPrefix()
      }

      fs.rename(files.file.path, `${config.get('uploadFolder')}/${siteName}/${prefix}${filename}`, function(err) {
        if (err) return rej(err)
        file.path = `${config.get('uploadFolder')}/${siteName}/${prefix}${filename}`
        file.filename = `${prefix}${filename}`

        return res(file)
      })
    })
  })
}
