const path = require('path');
const fs = require('fs');
const { lint } = require('kolibri-tools/lib/lint');

const languageInfo = require('../../kolibri/locale/language_info.json');

const commonHeader = `
/*
 * This is an auto-generated file, any manual edits will be overridden.
 *
 * To regenerate, see instructions here:
 *   https://kolibri-dev.readthedocs.io/en/develop/references/i18n.html
 *
 * This file was generated by frontend_build/src/intl_code_gen.js
 */
`;
const vueIntlHeader = `module.exports = function () {
  const data = [];`;

const generateVueIntlItems = language => {
  /*
   * Generate entries of this form:
   *   data.push(require('vue-intl/locale-data/ar.js'));
   *
   * Some Intl codes look like 'ar' and others look like 'bn-bd', so for Vue Intl
   * we strip off the territory code if it's there.
   */
  const vue_intl_code = language.intl_code.split('-')[0];
  return `data.push(require('vue-intl/locale-data/${vue_intl_code}.js'));`;
};

const vueIntlFooter = `
  return data;
};
`;

const vueIntlModule =
  commonHeader + vueIntlHeader + languageInfo.map(generateVueIntlItems).join('') + vueIntlFooter;

const vueIntlModulePath = path.resolve(
  __dirname,
  '../../kolibri/core/assets/src/utils/vue-intl-locale-data.js'
);

const intlHeader = `module.exports = function(locale) {
  switch (locale) {`;

const generateIntlItems = language => {
  /*
   * Generate entries of the form:
   *
   * case 'sw-tz':
   *   return new Promise(function(resolve) {
   *     require.ensure(
   *       ['intl/locale-data/jsonp/sw-TZ.js'],
   *       function(require) {
   *         resolve(() => require('intl/locale-data/jsonp/sw-TZ.js'));
   *       }
   *     );
   *   });
   *
   * Note that not all codes have two parts, e.g. 'en' vs 'es-mx'.
   */

  const codes = language.intl_code.split('-');
  let file_name = codes[0];
  if (codes.length > 1) {
    file_name += '-' + codes[1].toUpperCase();
  }
  return `
    case '${language.intl_code}':
      return new Promise(function(resolve) {
        require.ensure(
          ['intl/locale-data/jsonp/${file_name}.js'],
          function(require) {
            resolve(() => require('intl/locale-data/jsonp/${file_name}.js'));
          }
        );
      });`;
};

const intlFooter = `
    default:
      return new Promise(function(resolve) {
        require.ensure(
          ['intl/locale-data/jsonp/en.js'],
          function(require) {
            resolve(() => require('intl/locale-data/jsonp/en.js'));
          }
        );
      });
  }
};
`;

const intlModule =
  commonHeader + intlHeader + languageInfo.map(generateIntlItems).join('') + intlFooter;

const intlModulePath = path.resolve(
  __dirname,
  '../../kolibri/core/assets/src/utils/intl-locale-data.js'
);

fs.writeFileSync(vueIntlModulePath, vueIntlModule, { encoding: 'utf-8' });

fs.writeFileSync(intlModulePath, intlModule, { encoding: 'utf-8' });

lint({
  file: intlModulePath,
  write: true,
  silent: true,
});

lint({
  file: vueIntlModulePath,
  write: true,
  silent: true,
});

@@ -1780,52 +1780,302 @@
 %0A%0A  
-const codes = language.intl_code.split('-');
+// For examples, see:%0A  // https://github.com/andyearnshaw/Intl.js/tree/master/locale-data/jsonp%0A  const pattern = /%5E(%5Cw%7B2,3%7D)(-%5Cw%7B4%7D)?(-%5Cw%7B2%7D)?(-%5Cd+)?$/;%0A  const codes = language.intl_code.match(pattern);%0A  if (!codes) %7B%0A    console.error(%60Unable to parse code: '$%7Blanguage.intl_code%7D'%60);%0A  %7D%0A
 %0A  l
@@ -2085,23 +2085,114 @@
 file
-_
 name =
+ '';%0A%0A  // Always start with a 2- or 3-character sequence of lowercase letters%0A  filename +=
  codes%5B
-0
+1
 %5D;%0A 
@@ -2205,22 +2205,79 @@
 odes
-.length %3E 1) %7B
+%5B2%5D) %7B%0A    // Trailing four-letter strings of characters are Title-case
 %0A   
@@ -2277,25 +2277,24 @@
 ase%0A    file
-_
 name += '-' 
@@ -2301,16 +2301,19 @@
 + codes%5B
+2%5D%5B
 1%5D.toUpp
@@ -2320,21 +2320,253 @@
 erCase()
-;%0A  %7D
+ + codes%5B2%5D.substring(2)%0A  %7D%0A  if (codes%5B3%5D) %7B%0A    // Trailing two-letter strings of characters are CAPITAL-case%0A    filename += codes%5B3%5D.toUpperCase();%0A  %7D%0A  if (codes%5B4%5D) %7B%0A    // Trailing runs of numbers%0A    filename += codes%5B4%5D;%0A  %7D%0A
 %0A  retur
@@ -2705,33 +2705,32 @@
 ata/jsonp/$%7Bfile
-_
 name%7D.js'%5D,%0A    
@@ -2819,17 +2819,16 @@
 p/$%7Bfile
-_
 name%7D.js

update to capitalization code, ref #6796