// Based on https://github.com/airbnb/babel-plugin-dynamic-import-webpack
// We've added support for SSR with this version
import template from 'babel-template'
import syntax from 'babel-plugin-syntax-dynamic-import'
import { dirname, relative, resolve } from 'path'

const TYPE_IMPORT = 'Import'

const buildImport = (args) => (template(`
  (
    typeof window === 'undefined' ?
      new (require('next/same-loop-promise').default)((resolve, reject) => {
        eval('require.ensure = function (deps, callback) { callback(require) }')
        require.ensure([], (require) => {
          let m = require(SOURCE)
          m.__webpackChunkName = '${args.name}.js'
          resolve(m);
        }, 'chunks/${args.name}.js');
      })
      :
      new (require('next/same-loop-promise').default)((resolve, reject) => {
        const weakId = require.resolveWeak(SOURCE)
        try {
          const weakModule = __webpack_require__(weakId)
          return resolve(weakModule)
        } catch (err) {}

        require.ensure([], (require) => {
          try {
            let m = require(SOURCE)
            resolve(m)
          } catch(error) {
            reject(error)
          }
        }, 'chunks/${args.name}.js');
      })
  )
`))

export function getModulePath (sourceFilename, moduleName) {
  // resolve only if it's a local module
  const modulePath = (moduleName[0] === '.')
    ? resolve(dirname(sourceFilename), moduleName) : moduleName

  const cleanedModulePath = modulePath
    .replace(/(index){0,1}\.js$/, '') // remove .js, index.js
    .replace(/[/\\]$/, '') // remove end slash

  return cleanedModulePath
}

export default () => ({
  inherits: syntax,

  visitor: {
    CallExpression (path, state) {
      if (path.node.callee.type === TYPE_IMPORT) {
        const { opts } = path.hub.file

        const moduleName = path.node.arguments[0].value
        const currentDir = dirname(opts.filename)
        const modulePath = resolve(currentDir, moduleName)
        const chunkName = relative(opts.sourceRoot || process.cwd(), modulePath).replace(/[^\w]/g, '-')

        const newImport = buildImport({
          name: chunkName
        })({
          SOURCE: path.node.arguments
        })
        path.replaceWith(newImport)
      }
    }
  }
})

@@ -1828,50 +1828,399 @@
 nst 
-moduleName = path.node.arguments%5B0%5D.value%0A
+arg = path.node.arguments%5B0%5D%0A        const chunknameComment = arg.leadingComments && arg.leadingComments.map((%7Bvalue%7D) =%3E value.trim()).filter((value) =%3E /webpackChunkName:/.test(value))%5B0%5D%0A        const moduleRequest = arg.value%0A%0A        let chunkName%0A        if (chunknameComment) %7B%0A          chunkName = JSON.parse(chunknameComment.replace(/webpackChunkName:%5Cs*/, ''))%0A        %7D else %7B%0A  
     
@@ -2261,24 +2261,26 @@
 s.filename)%0A
+  
         cons
@@ -2320,20 +2320,23 @@
 , module
-Name
+Request
 )%0A      
@@ -2333,29 +2333,25 @@
 st)%0A        
-const
+ 
  chunkName =
@@ -2428,16 +2428,26 @@
 /g, '-')
+%0A        %7D
 %0A%0A      

Add support for webpackChunkName import comment