// VMWare Extension Installation
// Created by Nicolas Bidaux based on Jibson Mamerto specifications
// January 2025

getCompanyID = function (serverUrl,userToken) {
	// get the Company ID
	return new Promise((resolve, reject) => {
		$.ajax({
			url: serverUrl+"/WS2/OAuthService/currentCompanyId",
			type: "GET",
			dataType: 'json',
			contentType: 'application/json; charset=utf-8',
			success: function(companyID) {
				//console.log("Company ID:", companyID);
				resolve(companyID); // Resolve the Promise with the ID
			},
			beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer '+userToken); }, //set tokenString 
			error: function (xhr, status) {	console.log(xhr);	}
		});
	});
}

createVMWarequestion = function (serverUrl,companyId,userToken, questionVMWare) {
	// Create a question
		
	return $.ajax({
		async: true,
		url: serverUrl+"/WS2/domains/"+companyId+"/questions",
		type: 'POST',
		dataType: 'json',
		data: questionVMWare,
		contentType: 'application/json; charset=utf-8',
		success: function (question) {
							
			var questionTASId = question.result[0].id;
		},
		beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer '+userToken); }, //set tokenString 
		error: function (xhr, status) {	console.log(xhr);	}
	});

}

createVMWaresurvey = function (serverUrl,companyId,userToken, surveyVMWare) {
	// Create a survey 

	return $.ajax({
		async: true,
		url: serverUrl+"/WS2/domains/"+companyId+"/surveys",				
		type: 'POST',
		dataType: 'json',
		data: surveyVMWare,
		contentType: 'application/json; charset=utf-8',
		success: function (survey) {
							
			surveyId = survey.result[0].id;
			
		},
		beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer '+userToken); }, //set tokenString 
		error: function (xhr, status) {	console.log(xhr);	}
	});
}

createVMWareindicator = function (serverUrl,companyId,userToken, indicatorVMWare) {
	// Create a custom indicator 

	return $.ajax({
		async: true,
		url: serverUrl+"/WS/configuration?companySwitch="+companyId,				
		type: 'POST',
		dataType: 'json',
		data: indicatorVMWare,
		contentType: 'application/json; charset=utf-8',
		success: function (indicator) {
							
			indicatorId = indicator.result.id;
			
		},
		beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer '+userToken); }, //set tokenString 
		error: function (xhr, status) {	console.log(xhr);	}
	});
}

createCustomSegmentation = function (serverUrl,companyId,userToken, segmentationJSONfile) {
	// Load a Custom Segmentation 
	var formData = new FormData();
	formData.append("file", segmentationJSONfile);
	formData.append("textData", segmentationJSONfile.text());

	return $.ajax({
		async: true,
		url: serverUrl+"/WS2/domains/"+companyId+"/segmentations/upload",				
		type: 'POST',
		data: formData,
        processData: false,  // Prevent jQuery from processing the data
        contentType: false,  // Prevent jQuery from setting content type
		success: function (segmentation) {
							
			segmentationId = segmentation.id;
			//console.log(segmentationId);
		},
		beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer '+userToken); }, //set tokenString 
		error: function (xhr, status) {	console.log(xhr);	}
	});
}

/**
 * Function to create the custom segmentation JSON file for VMWare with the proper custom indicators IDs and load the segmentation in the HL instance.
 * @param {string} serverUrl
 * @param {string} companyId
 * @param {string} userToken
 * @param {string} indicatorTASID
 * @param {string} indicatorTKGID
 */
async function createSegmentationFile(serverUrl,companyId,userToken,indicatorTASID, indicatorTKGID) {
	var fileHandle;
	var fileContent = '{ \
    "segmentationGroupRef" : "TanzuSegmentation", \
    "name" : "VMware Current Application Landscape", \
    "description" : "This dashboard groups the applications based on their dependency on Tanzu.", \
    "segments" : [{ \
      "segmentRef" : "TanzuSegmentation_None", \
      "name" : "Standard VM Deployment", \
      "description" : "Applications traditionally deployed on VM with no direct dependencies on Tanzu.", \
      "color" : "#717074", \
      "matchingRules" : [ { \
        "description" : "No TAP Score or TKG Score", \
        "formula" : "(CIDTAS < 1 or CIDTAS =is= null) and (CIDTKG < 1 or CIDTKG =is= null)", \
        "points" : 10 \
      } ] \
    }, { \
      "segmentRef" : "TanzuSegmentation_TKG", \
      "name" : "Tanzu Kubernetes Grid (TKG)", \
      "description" : "Applications deployed using Tanzu Kubernetes Grid (TKG)", \
      "color" : "#78be20", \
      "matchingRules" : [ { \
        "description" : "Only TKG Score", \
        "formula" : "(CIDTAS < 1 or CIDTAS =is= null) and (CIDTKG > 0)", \
        "points" : 10 \
      } ] \
    }, { \
      "segmentRef" : "TanzuSegmentation_TAP", \
      "name" : "Tanzu Application Platform (TAP)", \
      "description" : "Applications deployed using Tanzu Application Platform (TAP)", \
      "color" : "#0091da", \
      "matchingRules" : [ { \
        "description" : "Only TAP Score", \
        "formula" : "(CIDTAS > 0) and (CIDTKG < 1 or CIDTKG =is= null)", \
        "points" : 10 \
      } ] \
    }, { \
      "segmentRef" : "TanzuSegmentation_TAP_TKG", \
      "name" : "TAP/TKG on VMware", \
      "description" : "Applications that are leveraging both TKG and TAP.", \
      "color" : "#1d428a", \
      "matchingRules" : [ { \
        "description" : "TAP and TKG Scores", \
        "formula" : "(CIDTAS > 0) and (CIDTKG > 0)", \
        "points" : 10 \
      } ] \
    } ], \
    "segmentationStatus" : "production" }';

	try {
		  const options = {
			suggestedName: "VMWareSegmentation.json",
			types: [
				{
					description: 'JSON Files',
					accept: {'text/plain': ['.json'],},
				},
				],
			};
		
		// Show file picker
		fileHandle = await window.showSaveFilePicker(options);

		// Get writable stream
		var writable = await fileHandle.createWritable();

		var modifiedContent = fileContent.replace(new RegExp('CIDTAS', "g"), indicatorTASID);
		modifiedContent = modifiedContent.replace(new RegExp('CIDTKG', "g"), indicatorTKGID);
		
		// Write modified content
		await writable.write(modifiedContent);
		await writable.close();	
		//alert("File modified and saved successfully!");
		$("#savecustomsegmentationfile").html('<div style="margin-top:24px">Custom VMWare segmentation file created successfully!</div><br>');
		
		modifiedFile = await fileHandle.getFile();
		//console.log(await modifiedFile.text())
		await createCustomSegmentation(serverUrl,companyId,userToken,modifiedFile)
		$("#customsegmentation").html('<div style="margin-top:24px">Custom VMWare Segmentation loaded successfully!</div><br>');

	} catch (err) {
		console.error("Error saving file:", err);
		}
}

loadVMWareExtension = function (serverUrl,userToken) {
	//Create the 2 questions then the survey and the custom indicator and it will finally load the custom segmentation

	getCompanyID(serverUrl,userToken).then(companyId => {
		$("#companyID").html('<div style="margin-top:24px">Company successfully retrieved : ' + companyId + '!</div><br>');

		// To create the TAS question
		var questionTAS = '[{"clientRef": "VMWARE_TAS","label": "[VMWare] What is the Tanzu Application Service (TAS) Score?","shortLabel": "TAS Score","description": "Answer by using the VMWare keyword scan results for Tanzu Application Service (TAS) score.","type": "number","position": 0}]';
		// To create the TKG question
		var questionTKG = '[{"clientRef": "VMWARE_TKG","label": "[VMWare] What is the Tanzu Kubernetes Grid (TKG) Score?","shortLabel": "TKG Score","description": "Answer by using the VMWare keyword scan results for Tanzu Kubernetes Grid (TKG) score.","type": "number","position": 1}]';

		Promise.all([createVMWarequestion(serverUrl,companyId,userToken, questionTAS), createVMWarequestion(serverUrl,companyId,userToken, questionTKG)])
			.then(([firstQuestion, secondQuestion]) => {
				// Both questions are created
				//console.log('First Question:', firstQuestion.result[0].id);
				//console.log('Second Question:', secondQuestion.result[0].id);
				$("#questions").html('<div style="margin-top:24px">2 questions created successfully!</div><br>');

				var surveyVMWare = '[{"ref":"VMWARE_Survey","name":"VMWare Tanzu Survey","description":"Survey used for the VMware Custom Segmentation.","questions":[{"id":'+firstQuestion.result[0].id+'},{"id":'+secondQuestion.result[0].id+'}]}]';
				//console.log(surveyVMWare);
				createVMWaresurvey(serverUrl,companyId,userToken,surveyVMWare)
				$("#survey").html('<div style="margin-top:24px">Survey created successfully!</div><br>');
				

				var indicatorVMWareTAS='{"computedMetricName":"Tanzu Application Service (TAS) Score","description":"Based on the VMWare Keyword scan results filled into the VMWare Survey.","metricOverridedLabel":null,"companyUnitId":null,"customized":true,"customRiskLevel":null,"requestedMetric":[{"metricId":'+firstQuestion.result[0].id+',"configurationElement":[{"type":"tag","metricTagId":1,"rangeMin":11.0,"rangeMax":-1.0,"weight":100.0},{"type":"tag","metricTagId":1,"rangeMin":-1.0,"rangeMax":0.0,"weight":0.0},{"type":"tag","metricTagId":1,"rangeMin":1.0,"rangeMax":10.0,"weight":50.0}]}]}'
				//console.log(indicatorVMWareTAS);

				var indicatorVMWareTKG='{"computedMetricName":"Tanzu Kubernetes Grid (TKG) Score","description":"Based on the VMWare Keyword scan results filled into the VMWare Survey.","metricOverridedLabel":null,"companyUnitId":null,"customized":true,"customRiskLevel":null,"requestedMetric":[{"metricId":'+secondQuestion.result[0].id+',"configurationElement":[{"type":"tag","metricTagId":1,"rangeMin":11.0,"rangeMax":-1.0,"weight":100.0},{"type":"tag","metricTagId":1,"rangeMin":-1.0,"rangeMax":0.0,"weight":0.0},{"type":"tag","metricTagId":1,"rangeMin":1.0,"rangeMax":10.0,"weight":50.0}]}]}'
				//console.log(indicatorVMWareTKG);
				
				Promise.all([createVMWareindicator(serverUrl,companyId,userToken,indicatorVMWareTAS), createVMWareindicator(serverUrl,companyId,userToken,indicatorVMWareTKG)])
					.then(([firstIndicator, secondIndicator]) => {
						// Both indicators are created
						//console.log(firstIndicator.result.id)
						//console.log(secondIndicator.result.id)
						
						$("#customindicators").html('<div style="margin-top:24px">2 custom indicators created successfully!</div><br>');
						createSegmentationFile(serverUrl,companyId,userToken,"CID"+firstIndicator.result.id,"CID"+secondIndicator.result.id)
					})
					.catch(error => {
					// Handle any error from the AJAX calls
						console.error('Error in AJAX calls:', error);	
					});			
				
				
			})
			.catch(error => {
			// Handle any error from the AJAX calls
				console.error('Error in AJAX calls:', error);	
			});
	}).catch(error => {
		console.error("Error Retrieving the Company ID:", error);
	});
}
