import { parseArticles, parseArticle } from '../base/article/util.mjs'
import { parseFiles } from './file/util.mjs'
import Parent from '../base/article/routes.mjs'
import { decodeTorrentFile } from './file/torrent.mjs'

export default class ArticleRoutes extends Parent {
  register(server) {
    super.register(server)
    server.flaska.post('/api/auth/articles/:id/files', [
      server.authenticate(),
      server.formidable({ maxFileSize: 100 * 1024 * 1024, }),
    ], this.auth_addFileToArticle.bind(this))
    server.flaska.delete('/api/auth/articles/:id/files/:fileId', [
      server.authenticate(),
    ], this.auth_removeFile.bind(this))
  }

  getArticle_resOutput(res) {
    return {
      article: parseArticle(res.results[0][0]),
      files: parseFiles(res.results[1]),
    }
  }

  private_getUpdateArticle_resOutput(res) {
    return {
      article: parseArticle(res.results[0][0] || {}),
      files: parseFiles(res.results[1]),
      staff: res.results[2],
    }
  }

  /** POST: /api/auth/articles/:id/files */
  async auth_addFileToArticle(ctx) {
    if (!ctx.req.files.file) {
      throw new HttpError(422, 'Missing file in upload')
    }

    let meta = {}
    if (ctx.req.files.file.name.endsWith('.torrent')) {
      try {
        let torrent = await decodeTorrentFile(ctx.req.files.file.path)
        meta.torrent = {
          name: torrent.name,
          announce: torrent.announce,
          hash: torrent.infoHash,
          files: torrent.files.map(file => ({ name: file.name, size: file.length })),
        }
      } catch (err) {
        ctx.log.error(err)
      }
    }
    let file = await this.uploadFile(ctx.req.files.file)

    let params = [
      ctx.state.auth_token,
      ctx.params.id,
      file.filename,
      file.type,
      file.path,
      file.size,
      JSON.stringify(meta),
      null,
      0,
    ]

    await ctx.db.safeCallProc('article_auth_file_create_delete', params)
  }

  /** DELETE: /api/auth/articles/:id/files/:fileId */
  async auth_removeFile(ctx) {
    let params = [
      ctx.state.auth_token,
      ctx.params.id,
      null,
      null,
      null,
      null,
      null,
      ctx.params.fileId,
      1,
    ]

    let res = await ctx.db.safeCallProc('article_auth_file_create_delete', params)
    await this.deleteFile(res.first[0].deleted_filename)
  }
}