import * as flashpoint from 'flashpoint-launcher';
import * as path from 'path';
import * as fs from 'fs';

export function activate(context: flashpoint.ExtensionContext) {
	flashpoint.registerDisposable(context.subscriptions, flashpoint.curations.onWillGenCurationWarnings((event) => {
		const { game } = event.curation;
		// Checks for HTTPS and non-existant launch command files
		if (game.launchCommand) {
			const launchWarns = invalidLaunchCommandWarnings(getContentFolder(event.curation.folder), game.launchCommand);
			for (const w of launchWarns) {
				event.warnings.writtenWarnings.push(w);
				event.warnings.fieldWarnings.push('launchCommand');
			}
		}
		
		// Warn of no notes of Hacked and Partial
		if (game.status && !game.notes) {
			if (game.status.includes('Hacked') || game.status.includes('Partial')) {
				event.warnings.writtenWarnings.push('documentStatus');
				event.warnings.fieldWarnings.push('notes');
			}
		}
	}));
}

// this method is called when your extension is deactivated (Currently unused)
export function deactivate() {}

function getContentFolder(folder: string): string {
	return path.join(flashpoint.curations.getCurationPath(folder), 'content');
}

function invalidLaunchCommandWarnings(folderPath: string, launchCommand: string): string[] {
	// Keep list of warns for end
	const warns: string[] = [];
	// Extract first string from launch command via regex
	const match = launchCommand.match(/[^\s"']+|"([^"]*)"|'([^']*)'/);
	if (match) {
	  // Match 1 - Inside quotes, Match 0 - No Quotes Found
	  let lc = match[1] || match[0];
	  // Extract protocol from potential URL
	  const protocol = lc.match(/(.+?):\/\//);
	  if (protocol) {
		// Protocol found, must be URL
		if (protocol[1] !== 'http') {
		  // Not using HTTP
		  warns.push('ilc_notHttp');
		}
		const ending = lc.split('/').pop();
		// If the string ends in file, cut off parameters
		if (ending && ending.includes('.')) {
		  lc = lc.split('?')[0];
		}
		const filePath = path.join(folderPath, unescape(lc).replace(/(^\w+:|^)\/\//, ''));
		// Push a game to the list if its launch command file is missing
		if (!fs.existsSync(filePath)) {
		  warns.push('ilc_nonExistant');
		}
	  }
	}
	return warns;
  }