const path = require('path')
const globby = require('globby')
const sucrase = require('@rollup/plugin-sucrase')
const { externalizeRelative } = require('./scripts/lib/new-rollup')

/*
needs locales-all to run first

compiles from *SRC* files.
we use sucrase to transpile the ts files.
normally we wouldn't use sucrase because it produces JS that's too advanced for the browsers we want to support,
but the locale files are simple so it'll be fine.
*/

let srcLocaleFiles = globby.sync('packages/core/src/locales/*.ts')
let bundleDirs = globby.sync('packages?(-premium)/bundle', { onlyDirectories: true })
let sucraseInstance = sucrase({
  transforms: ['typescript']
})

module.exports = [

  // locales-all.js, for CORE
  {
    input: 'packages/core/src/locales-all.ts',
    output: {
      format: 'es',
      file: 'packages/core/locales-all.js'
    },
    plugins: [
      externalizeRelative(), // resulting bundle will import the individual locales
      sucraseInstance
    ]
  },

  // locales-all.js, for BUNDLES
  {
    input: 'packages/core/src/locales-all.ts',
    output: bundleDirs.map((bundleDir) => ({
      format: 'iife',
      name: 'FullCalendar',
      file: path.join(bundleDir, 'locales-all.js')
    })),
    plugins: [
      sucraseInstance,
      bundleWrapLocalesAll()
    ]
  },

  // locales/*.js, for CORE
  ...srcLocaleFiles.map((localeFile) => ({
    input: localeFile,
    output: {
      format: 'es',
      file: path.join('packages/core/locales', path.basename(localeFile))
    },
    plugins: [
      sucraseInstance
    ]
  })),

  // locales/*.js, for BUNDLES
  ...srcLocaleFiles.map((localeFile) => ({
    input: localeFile,
    output: bundleDirs.map((bundleDir) => ({
      format: 'iife',
      name: 'FullCalendar',
      file: path.join(bundleDir, 'locales', path.basename(localeFile))
    })),
    plugins: [
      sucraseInstance,
      bundleWrapLocalesEach()
    ]
  }))

]


function bundleWrapLocalesAll() {
  return {
    renderChunk(code) {
      return code.replace(/^var FullCalendar = /, 'FullCalendar.globalLocales = ')
    }
  }
}


function bundleWrapLocalesEach() {
  return {
    renderChunk(code) {
      return code.replace(/^var FullCalendar = /, 'FullCalendar.globalLocales.push')
    }
  }
}

@@ -1344,33 +1344,36 @@
 ocaleFiles.map((
-l
+srcL
 ocaleFile) =%3E (%7B
@@ -1376,33 +1376,36 @@
 %3E (%7B%0A    input: 
-l
+srcL
 ocaleFile,%0A    o
@@ -1486,33 +1486,36 @@
 , path.basename(
-l
+srcL
 ocaleFile))%0A    
@@ -1503,25 +1503,40 @@
 rcLocaleFile
-)
+, '.ts') + '.js'
 )%0A    %7D,%0A   
@@ -1639,17 +1639,20 @@
 es.map((
-l
+srcL
 ocaleFil
@@ -1671,17 +1671,20 @@
  input: 
-l
+srcL
 ocaleFil
@@ -1839,17 +1839,20 @@
 asename(
-l
+srcL
 ocaleFil
@@ -1852,17 +1852,32 @@
 caleFile
-)
+, '.ts') + '.js'
 )%0A    %7D)
@@ -2072,36 +2072,52 @@
  FullCalendar = 
+%5C(
 /, '
+%5B%5D.push.apply(
 FullCalendar.glo
@@ -2130,13 +2130,56 @@
 ales
- = ')
+, ') // needs to be by-reference. can't reassign
 %0A   

fix globalLocales issues