
// const path = require('path')
// const fs = require('fs')
const vueComponentCompiler = require('@vue/component-compiler-utils');
const VueTemplateCompiler = require('vue-template-compiler');

module.exports = function blSappServicePreLoader (source) {
  if (source.substr(0, 34) === '<!-- webview only --><!-- slot -->') {
    return `<template><div><slot></slot></div></template><script>export default { methods: {}, beforeDestroy() { delete this.$root.$page.components[this._bili_id || this._uid] } }</script>`;
  }

  if (source.substr(0, 21) === '<!-- webview only -->') {
      return `<template><div></div></template><script>export default { methods: {}, beforeDestroy() { delete this.$root.$page.components[this._bili_id || this._uid] } }</script>`;
  }

  let vueSFCDescriptor = vueComponentCompiler.parse({
    source,
    compiler: VueTemplateCompiler,
    needMap: false
  });

  const attrsTemplate = []
    Object.keys(vueSFCDescriptor.template.attrs).forEach(attr => {
        attrsTemplate.push(`${attr}="${vueSFCDescriptor.template.attrs[attr]}"`)
    })

  const attrsScript = []
  Object.keys(vueSFCDescriptor.script.attrs).forEach(attr => {
      attrsScript.push(`${attr}="${vueSFCDescriptor.script.attrs[attr]}"`)
  })

  return `
    <template ${attrsTemplate.join(' ')}>
      ${vueSFCDescriptor.template.content}
    </template>
    <script ${attrsScript.join(' ')}>
      ${vueSFCDescriptor.script.content}
    </script>
  `
}