#!/user/bin/env nodejs
'use strict';

const fs = require('fs');
const svelte = require('svelte/compiler');

let pnotifyComponents = [
  // Main code.
  'PNotifyCoreComponent',
  'PNotifyAnimateComponent',
  'PNotifyButtonsComponent',
  'PNotifyMobileComponent',
  'PNotifyHistoryComponent',
  'PNotifyDesktopComponent',
  'PNotifyConfirmComponent'

  // Styles.
  'PNotifyStyleMaterialComponent',

  // Reference module.
  'PNotifyReferenceComponent',
];

let pnotifySrc = [
  // Main code.
  'PNotifyCore',
  'PNotifyAnimate',
  'PNotifyButtons',
  'PNotifyMobile',
  'PNotifyHistory',
  'PNotifyDesktop',
  'PNotifyConfirm',
  'PNotifyCallbacks',

  // Styles.
  'PNotifyStyleMaterial',

  // Reference module.
  'PNotifyReference',
];

try {
  fs.mkdirSync('dist');
} catch (e) {}
try {
  fs.mkdirSync('dist/es');
} catch (e) {}

// Compile Svelte component.
for (let name of pnotifyComponents) {
  const srcFilename = 'src/' + name + '.html';
  const dstFilename = 'dist/es/' + name + '.js';
  let code = fs.readFileSync(srcFilename, 'utf8');
  let map;

  const { js } = svelte.compile(code, {
    format: 'esm',
    filename: srcFilename,
    name,
    css: false
  });
  ({ code, map } = js);
  if (map) {
    code += '\n//# sourceMappingURL=' + name + '.js.map';
  }

  fs.writeFileSync(dstFilename, code);
  if (map) {
    fs.writeFileSync(dstFilename + '.map', JSON.stringify(map));
  }
}

// Alter module to import correctly.
for (let name of pnotifySrc) {
  const srcFilename = 'src/' + name + '.js';
  const dstFilename = 'dist/es/' + name + '.js';
  let code = fs.readFileSync(srcFilename, 'utf8');

  code = code.replace(/import (.*) from (["'])\.\/(\w*)\.html(["'])/g, 'import $1 from $2./$3$4');

  fs.writeFileSync(dstFilename, code);
}

@@ -101,18 +101,20 @@
 ler');%0A%0A
-le
+cons
 t pnotif
@@ -243,43 +243,15 @@
 tify
-MobileComponent',%0A  'PNotifyHistory
+Confirm
 Comp
@@ -289,39 +289,39 @@
 ent',%0A  'PNotify
-Confirm
+History
 Component'%0A%0A  //
@@ -318,46 +318,26 @@
 ent'
-%0A%0A  // Styles.%0A  'PNotifyStyleMaterial
+,%0A  'PNotifyMobile
 Comp
@@ -401,16 +401,17 @@
 ent'
-,
 %0A%5D;%0A%0A
-le
+cons
 t pn
@@ -506,22 +506,25 @@
 'PNotify
-Mobile
+Callbacks
 ',%0A  'PN
@@ -528,23 +528,23 @@
 'PNotify
-History
+Confirm
 ',%0A  'PN
@@ -560,39 +560,39 @@
 top',%0A  'PNotify
-Confirm
+History
 ',%0A  'PNotifyCal
@@ -592,57 +592,14 @@
 tify
-Callbacks',%0A%0A  // Styles.%0A  'PNotifyStyleMaterial
+Mobile
 ',%0A%0A
@@ -641,17 +641,16 @@
 ference'
-,
 %0A%5D;%0A%0Atry
@@ -770,26 +770,28 @@
 onent.%0Afor (
-le
+cons
 t name of pn
@@ -1351,18 +1351,20 @@
 y.%0Afor (
-le
+cons
 t name o

Fix make script.