const path = require('path')
const url = require('url')
const youtube = require('./utils/youtube.js')
const jobs = require('./jobs')
const { rewriteURL } = require('./urls')

const generateImage = (file, targetDir, width, height) =>
  jobs.run('imageResizer', file, targetDir, width, height)

const paramInHrefParser = href => {
  const sepIndex = href.indexOf(' =')
  const ret = {
    href,
    options: {},
  }
  if (sepIndex < 0) {
    return ret
  }
  ret.href = href.substr(0, sepIndex)
  let options = href.substr(sepIndex + 2)
  options = options // split by ',' but not '\,'
    .replace('a,', '\u0007')
    .split(',')
    .map(e => e.replace('\u0007', 'a,'))
  options.forEach(option => {
    const index = option.indexOf('=')
    if (index < 0) {
      ret.options[option] = true
    } else {
      const key = option.substr(0, index)
      const value = option.substr(index + 1)
      ret.options[key] = value
    }
  })
  return ret
}

const renderYoutube = href => {
  const info = youtube.info(href)
  let out = '<div class="video-container"><div class="videodiv">'
  out += `${`<iframe src="https://www.youtube.com/embed/${info.videoid}` +
    '?modestbranding&start='}${
    info.time
  }" frameborder="0" allowfullscreen></iframe>`
  out += '</div></div>'

  return out
}

module.exports = (href_, title, text, curFile_, cfg) => {
  let curFile = curFile_
  const parsed = paramInHrefParser(href_)
  const { href } = parsed
  const { options } = parsed

  for (const option of Object.keys(options)) {
    if (option.match(/x[0-9]+/) || option.match(/[0-9]+x[0-9]*/)) {
      // 123x or x123 or 123x123
      options.size = option.split('x')
      if (options.size !== undefined) {
        if (options.size[0].length > 0) {
          options.width = options.size[0]
        }
        if (options.size.length > 1 && options.size[1].length > 0) {
          options.height = options.size[1]
        }
      }
    }
  }

  if (youtube.isVideo(href)) {
    return renderYoutube(href, options)
  }
  const genHTML = (file, norel) => {
    const rel = file
    if (!norel) path.relative(process.cwd(), file)

    let out = `<img src="${rel}" alt="${text}"`
    if (options.width) {
      out += ` width="${options.width}"`
    }
    if (options.height) {
      out += ` height="${options.height}"`
    }
    if (title) {
      out += ` title="${title}"`
    }

    out += '>'
    if (!options.nolightbox) {
      // if lightbox
      let a = `<a href="${href}"`
      a += ' data-lightbox="group"'
      a += ` data-title="${text}"`
      a += '>'
      out = `${a + out}</a>`
    }
    return out
  }
  const parsedHref = url.parse(href)

  if (parsedHref.host) {
    return genHTML(href, true)
  }
  if (path.isAbsolute(href)) {
    return genHTML(href)
  }
  curFile = curFile.replace(/\.md$/, '')
  let targetDir = rewriteURL(curFile)
  targetDir = path.resolve(cfg.builddir, targetDir)
  const absSrc = path.resolve(cfg.staticDir, curFile, href)

  if (!options.size) options.size = []
  let w = options.size[0]
  let h = options.size[1]
  if (w === '') w = undefined
  else w = Number(w)
  if (h === '') h = undefined
  else h = Number(h)
  if (w === undefined && h === undefined) w = 512
  const file = generateImage(absSrc, targetDir, w, h)
  return genHTML(file)
}

module.exports._test = {
  paramInHrefParser,
}