// Builtins
var fs = require('fs')
var path = require('path')

// Devdeps.
// eslint-disable-next-line node/no-unpublished-require
var rimraf = require('rimraf')

// Tools
var mappingToJs = require('./tools/mapping-to-js')
var createIndex = require('./tools/create-index')
var cleanupPackageJson = require('./tools/cleanup-package-json')

var resolvePath = path.resolve.bind(path, __dirname)

// First, remove dist directory entirely
rimraf.sync(resolvePath('dist'))

// Create dist directory anew
fs.mkdirSync(resolvePath('dist'))

// Get a list of mapping files
var mappingNames = (fs
  .readdirSync(resolvePath('src', 'layouts'))
  .filter(function (filename) {
    return path.extname(filename) === '.json'
  })
  .map(function (filename) {
    return path.basename(filename, '.json')
  })
  .sort()
)

// Convert each json file to js with string mappings
var mappingTemplate = (fs
  .readFileSync(
    resolvePath('src', 'templates', 'locale.template.js')
  )
  .toString('utf-8')
)
for (var i = 0; i < mappingNames.length; i++) {
  var mapping = JSON.parse(fs
    .readFileSync(
      resolvePath('src', 'layouts', mappingNames[i] + '.json')
    )
    .toString('utf-8')
  )
  fs.writeFileSync(
    resolvePath('dist', mappingNames[i] + '.js'),
    mappingToJs(mapping, mappingTemplate)
  )
}

// Create index file
fs.writeFileSync(
  resolvePath('dist', 'index.js'),
  createIndex(mappingNames)
)

// Copy cleaned package.json
fs.writeFileSync(
  resolvePath('dist', 'package.json'),
  cleanupPackageJson(
    fs
      .readFileSync(
        resolvePath('package.json')
      )
      .toString('utf-8')
  )
)

// Copy files as-is
fs.copyFileSync(
  resolvePath('CHANGELOG.md'),
  resolvePath('dist', 'CHANGELOG.md')
)
fs.copyFileSync(
  resolvePath('README.md'),
  resolvePath('dist', 'README.md')
)
fs.copyFileSync(
  resolvePath('LICENSE'),
  resolvePath('dist', 'LICENSE')
)
fs.copyFileSync(
  resolvePath('src', 'convert.js'),
  resolvePath('dist', 'convert.js')
)

@@ -1608,17 +1608,18 @@
 ')%0A  )%0A)
+;
 %0A
-
 %0A// Copy
@@ -1631,34 +1631,31 @@
 s as-is%0A
-fs.copyFileSync(%0A 
+%5B%0A  %7B%0A    from:
  resolve
@@ -1669,32 +1669,38 @@
 HANGELOG.md'),%0A 
+   to:
  resolvePath('di
@@ -1720,36 +1720,34 @@
 OG.md')%0A
-)%0Afs.copyFileSync(%0A 
+  %7D,%0A  %7B%0A    from:
  resolve
@@ -1762,24 +1762,30 @@
 ADME.md'),%0A 
+   to:
  resolvePath
@@ -1806,36 +1806,34 @@
 ME.md')%0A
-)%0Afs.copyFileSync(%0A 
+  %7D,%0A  %7B%0A    from:
  resolve
@@ -1846,24 +1846,30 @@
 LICENSE'),%0A 
+   to:
  resolvePath
@@ -1892,28 +1892,26 @@
 E')%0A
-)%0Afs.copyFileSync(%0A 
+  %7D,%0A  %7B%0A    from:
  res
@@ -1942,16 +1942,22 @@
 .js'),%0A 
+   to:
  resolve
@@ -1983,10 +1983,190 @@
 rt.js')%0A
+  %7D%0A%5D.forEach(function (def) %7B%0A  fs.copyFile(%0A    def.from,%0A    def.to,%0A    function (err) %7B%0A      if (err) %7B%0A        console.error(err)%0A        process.exit(1)%0A      %7D%0A    %7D%0A  )%0A%7D
 )%0A

Fix file copying for Node < 8.5.0