const debug = require('debug')('banner:update-color-bg')
const fs = require('fs-extra')
const cheerio = require('cheerio')
const {
  tempPath,
  folderExists,
} = require('../utils')

const data = function data(color) {
  return `
    function serviceCallback (e) {
      fireFunction(e)

      var g = new createjs.Graphics()
      g.beginStroke('${color}').setStrokeStyle(10).drawRect(0, 0, 240, 400)
      var s = new createjs.Shape(g)
      exportRoot.addChild(s)
    }
  `
}

const replace = function replaceFn(str) {
  let i = -1

  return str.replace(/(handleComplete)+/ig, () => {
    i++
    return i === 0 ? 'serviceCallback' : 'fireFunction'
  })
}

async function updateBorder(ctx) {
  const { body } = ctx.request
  const { nameFolder, color, nameFile } = body
  const { process } = tempPath()

  debug('color change -', body)
  try {
    const $ = cheerio.load(await fs.readFile(process(`${nameFolder}/${nameFile}`)))
    let script

    $('script').each(function each() {
      if ($(this).attr('src') === undefined) {
        const str = replace($(this).html())

        $(this).append(`${str} ${data(color)}`)
        script = `${str} ${data(color)}`
      }
    })
    await fs.writeFile(process(`${nameFolder}/${nameFile}`), $.html())
    ctx.body = 'border color updated!'
  }
  catch (error) {
    ctx.throw(error)
  }
}

module.exports = (router, method, uri) => router[method](
  uri,
  folderExists(tempPath().process), updateBorder
)