import config from '../../base/config.mjs'
import Client from '../../base/media/client.mjs'
import OriginalArticleRoutes from '../../base/article/routes.mjs'
import { deleteFile, uploadFile } from '../../base/media/upload.mjs'
import { parseVideos, parseVideo } from './util.mjs'
import { RankLevels } from '../../base/authentication/security.mjs'

export default class ArticleRoutes extends OriginalArticleRoutes {
  constructor(opts = {}) {
    opts.requireAuth = true
    super(opts)

    Object.assign(this, {
      uploadFile: uploadFile,
      deleteFile: deleteFile,
    })
  }

  register(server) {
    server.flaska.get('/api/articles', this.getVideos.bind(this))
    server.flaska.get('/api/articles/:path', this.getArticle.bind(this))
    server.flaska.put('/api/auth/articles/:id', [server.authenticate(), server.jsonHandler()], this.updateCreateArticle.bind(this))
    server.flaska.get('/api/auth/uploadToken', server.authenticate(RankLevels.Admin), this.getUploadToken.bind(this))
    server.flaska.delete('/api/auth/articles/:id', server.authenticate(RankLevels.Admin), this.auth_removeSingleArticle.bind(this))
  }

  /** GET: /api/auth/articles */
  async getVideos(ctx) {
    let res = await ctx.db.safeCallProc('filadelfia_archive.article_get_all', [])

    ctx.body = {
      videos: parseVideos(res.results[0]),
    }
  }

  /** GET: /api/auth/uploadToken */
  async getUploadToken(ctx) {
    const media = config.get('media')

    ctx.body = {
      token: Client.createJwt({ iss: media.iss }, media.secret),
      path: config.get('media:directFilePath'),
      resize: config.get('media:path'),
      delete: config.get('media:removePath'),
    }
  }

  /** PUT: /api/auth/articles/:id */
  async updateCreateArticle(ctx) {
    return this.private_getUpdateArticle(ctx, ctx.req.body, ctx.req.body.banner, ctx.req.body.media)
  }
}
