import { uploadMedia } from '../base/media/upload.mjs'
import config from '../base/config.mjs'

export default class IndexPost {
  constructor(opts = {}) {
    Object.assign(this, {
      frontend: opts.frontend,
      uploadMedia: uploadMedia,
    })
  }

  register(server) {
    this.serve = server.routes.serve
    server.flaska.post('/', [
      server.formidable({ maxFileSize: 8 * 1024 * 1024, }),
    ], this.createNewLink.bind(this))
  }

  hasErrors(ctx, hasMedia) {
    if (!ctx.req.body.video) {
      return 'Missing video link'
    }

    if (!ctx.req.body.video.startsWith('http')
        || !(ctx.req.body.video.includes('mp4')
          || ctx.req.body.video.includes('webm'))) {
      return 'Video link has to be a valid full url and contain mp4 or webm in it'
    }

    if (!ctx.req.body.image && !hasMedia) {
      return 'Missing image link or file'
    }
    
    if (ctx.req.body.image) {
      if (!ctx.req.body.image.startsWith('http')
          || !(ctx.req.body.image.includes('jpg')
            || ctx.req.body.image.includes('jpeg')
            || ctx.req.body.image.includes('webp')
            || ctx.req.body.image.includes('png')
            )
          ) {
        return 'Image link has to be a valid full url and contain jpg, jpeg, webp or png'
      }
    }
  }

  /** PUT: /api/auth/articles/:id */
  async createNewLink(ctx) {
    let hasMedia = ctx.req.files.media && ctx.req.files.media.size
    
    ctx.state.video = ctx.req.body.video
    ctx.state.image = ctx.req.body.image
    let redirect = ''
    let error = this.hasErrors(ctx, hasMedia)

    if (!error && hasMedia) {
      try {
        let temp = await this.uploadMedia(ctx.req.files.media)
        ctx.state.image = ctx.req.body.image = 'https://cdn.nfp.is' + temp.sizes.small.jpeg.path
      }
      catch (err) {
        ctx.log.error(err)
        error = 'Unable to upload file: ' + err.message
      }
    }
    if (!error) {
      redirect = `${this.frontend}/?v=${ctx.state.video}&i=${ctx.state.image}`
    }

    if (!error) {
      try {
        let params = [
        ]
        let res = await ctx.db.safeCallProc('discord_embed.link_add', params)
        console.log(res)
      }
      catch (err) {
        ctx.log.error(err)
        error = 'Error while generating shortened link.'
      }
    }

    if (redirect && !error) {
      ctx.status = 302
      ctx.headers['Location'] = redirect
      ctx.type = 'text/html; charset=utf-8'
      ctx.body = `
Redirecting
<a href="${redirect}">Click here if it doesn't redirect</a>
`
    }
    ctx.state.error = error
    return this.serve.serveIndex(ctx)
  }
}
// https://litter.catbox.moe/cnl6hy.mp4