const {createDir, copyDir, color, delDir} = require('./helpers');
const {exec} = require('child_process');
const fs = require('fs');
const process = require('process');
const util = require('util');

const execShellCommand = util.promisify(exec);

async function main() {
	// Empty print line to pretty-ify command line output
	console.log();

	// Copy webview test environment locally if it does not already exist
	if (!fs.existsSync('./test-webview')) {
		try {
			console.log(color(['dim'], 'Copying webview test environment locally...'));
			await execShellCommand('npx degit microsoft/vscode-webview-ui-toolkit-samples/default/all-components test-webview');
		} catch (err) {
			console.log(`${color(['red'], 'Error: Could not copy webview test environment locally')}\n    ${err}`);
			process.exit();
		}
	}

	// Install the webview test environment dependencies if they do not exist
	if (!fs.existsSync('./test-webview/node_modules')) {
		try {
			console.log(color(['dim'], 'Installing webview test environment dependencies...'));
			await execShellCommand('cd ./test-webview && npm install');
		} catch (err) {
			console.log(`${color(['red'], 'Error: Could not install webview test environment dependencies')}\n    ${err}`);
			process.exit();
		}
	}

	// Copy latest toolkit build into the webview test environment
	try {
		console.log(color(['dim'], 'Copying latest toolkit build into webview test environment...'));
		// Copy web component build directory
		delDir('./test-webview/node_modules/@vscode/webview-ui-toolkit/dist');
		createDir('./test-webview/node_modules/@vscode/webview-ui-toolkit/dist');
		copyDir('./dist', './test-webview/node_modules/@vscode/webview-ui-toolkit');
		// Copy react build directory
		delDir('./test-webview/node_modules/@vscode/webview-ui-toolkit/react');
		createDir('./test-webview/node_modules/@vscode/webview-ui-toolkit/react');
		copyDir('./react', './test-webview/node_modules/@vscode/webview-ui-toolkit');
	} catch (err) {
		console.log(`${color(['red'], 'Error: Failed to copy latest toolkit build into webview test environment')}\n    ${err}`);
		process.exit();
	}

	// Print success and next steps messages
	console.log();
	console.log(color(['bold', 'green'], 'Webview test environment successfully configured!'));
	console.log();
	console.log('Next steps:');
	console.log(`  1. Open the ${color(['cyan'], 'test-webview')} folder in a new VS Code window`);
	console.log(`  2. Press ${color(['cyan'], 'F5')} to open the webview test extension with the most recent toolkit build loaded`);
	console.log(`  3. Run the "${color(['cyan'], 'Webview UI Toolkit: Open all components gallery')}" command using the VS Code command palette`);
	console.log();
}

main();

@@ -629,12 +629,8 @@
 ult/
-all-
 comp
@@ -634,17 +634,24 @@
 omponent
-s
+-gallery
  test-we
@@ -2593,46 +2593,17 @@
 %5D, '
-Webview UI Toolkit: Open all c
+C
 omponent
 s ga
@@ -2602,17 +2602,22 @@
 nent
-s g
+ G
 allery
+: Show
 ')%7D%22

Update `test:webview` script (#339)