/* eslint-disable */
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';

const __dirname = path.dirname( fileURLToPath( import.meta.url ) );
const inputPath = path.resolve( __dirname, '../src/castFunctions.template.js' );
const outputPath = path.resolve( __dirname, '../src/castFunctions.js' );
let contents = fs.readFileSync( inputPath, { encoding: 'utf8' } );

// contents = replaceFunctionMacro( contents, 'IS_LEAF', '( uint16Array[ $1 + 15 ] === 0xFFFF )' );
// contents = replaceFunctionMacro( contents, 'OFFSET', 'uint32Array[ $1 + 6 ]' );
// contents = replaceFunctionMacro( contents, 'COUNT', 'uint16Array[ $1 + 14 ]' );
// contents = replaceFunctionMacro( contents, 'LEFT_NODE', '$1 + 8' );
// contents = replaceFunctionMacro( contents, 'RIGHT_NODE', 'uint32Array[ $1 + 6 ]' );
// contents = replaceFunctionMacro( contents, 'SPLIT_AXIS', 'uint32Array[ $1 + 7 ]' );
// contents = replaceFunctionMacro( contents, 'BOUNDING_DATA_INDEX', '$1' );
contents = contents.replace( /^\/\*[\S\s]*?\*\//g, '/* Generated from "castFunctions.template.js". Do not edit. */' );

fs.writeFileSync( outputPath, contents );

function replaceFunctionMacro( contents, name, body ) {

	const regexp = new RegExp( `${ name }\\((.*?)\\)`, 'g' );
	return contents.replace( regexp, ( match, arg ) => {

		return body.replace( /\$1/g, arg.trim() );

	} );

}

@@ -388,19 +388,16 @@
 ' %7D );%0A%0A
-// 
 contents
@@ -445,27 +445,18 @@
 AF', '( 
-uint16Array
+$2
 %5B $1 + 1
@@ -472,27 +472,24 @@
 xFFFF )' );%0A
-// 
 contents = r
@@ -526,35 +526,26 @@
  'OFFSET', '
-uint32Array
+$2
 %5B $1 + 6 %5D' 
@@ -539,35 +539,32 @@
 2%5B $1 + 6 %5D' );%0A
-// 
 contents = repla
@@ -604,19 +604,10 @@
 ', '
-uint16Array
+$2
 %5B $1
@@ -614,27 +614,24 @@
  + 14 %5D' );%0A
-// 
 contents = r
@@ -682,27 +682,24 @@
 '$1 + 8' );%0A
-// 
 contents = r
@@ -740,35 +740,26 @@
 GHT_NODE', '
-uint32Array
+$2
 %5B $1 + 6 %5D' 
@@ -757,27 +757,24 @@
 1 + 6 %5D' );%0A
-// 
 contents = r
@@ -823,19 +823,10 @@
 ', '
-uint32Array
+$2
 %5B $1
@@ -840,11 +840,8 @@
  );%0A
-// 
 cont
@@ -1130,16 +1130,95 @@
 dy ) %7B%0A%0A
+%09const functionRegexp = new RegExp( %60function%5C%5Cs+$%7B name %7D%5B%5E%7B%5D+%7B%5B%5E%7D%5D+%7D%5Cn%5Cn%60 );%0A
 %09const r
@@ -1238,16 +1238,28 @@
 egExp( %60
+(function )?
 $%7B name 
@@ -1288,32 +1288,93 @@
 %09return contents
+%0A%09%09.replace( functionRegexp, () =%3E %7B%0A%0A%09%09%09return '';%0A%0A%09%09%7D )%0A%09%09
 .replace( regexp
@@ -1383,16 +1383,27 @@
 ( match,
+ funcToken,
  arg ) =
@@ -1413,52 +1413,201 @@
 %0A%0A%09%09
-return body.replace( /%5C$1/g, arg.trim() );%0A%0A
+%09let result = body;%0A%09%09%09const args = arg.split( /,/g );%0A%09%09%09for ( let i = 0; i %3C args.length; i ++ ) %7B%0A%0A%09%09%09%09result = result.replace( %60$$%7B i + 1 %7D%60, args%5B i %5D.trim() );%0A%0A%09%09%09%7D%0A%0A%09%09%09return result;%0A%0A%09
 %09%7D )

Fix cast function generator