'use strict';

var PopupBanPlayer = ( function(){

	var _Init = function ()
	{
		var xuid = $.GetContextPanel().GetAttributeString( "xuid", "" );
		var type = $.GetContextPanel().GetAttributeString( "type", "ban" );
		$.GetContextPanel().SetDialogVariable( "target_player", GameStateAPI.GetPlayerName( xuid ));

		var config = $.LoadKeyValuesFile('panorama/admin_ban_popup.res');
		var defaultSelected = config[type]['default'];

		Object.entries(config['types']).forEach(([name, label]) => {
			var optionLabel = $.CreatePanel('Label', $('#types'), name, { text: label });
			$('#types').AddOption(optionLabel);
		});
		$('#types').SetSelectedIndex(0);

		Object.entries(config[type]['reasons']).forEach(([name]) => {
			var optionLabel = $.CreatePanel('Label', $('#reasons'), name, { text: name });
			$('#reasons').AddOption(optionLabel);
		});
		$('#reasons').SetSelected(Object.keys(defaultSelected)[0]);

		Object.entries(config['time']).forEach(([time, label]) => {
			var optionLabel = $.CreatePanel('Label', $('#times'), time, { text: label });
			$('#times').AddOption(optionLabel);
		});
		$('#times').SetSelected(defaultSelected[Object.keys(defaultSelected)[0]]);
	}

	function _OnTypeChange()
	{
		var type = $('#types').GetSelected().id;

		if(type == 'gag' || type == 'silence')
			type = 'mute';

		var config = $.LoadKeyValuesFile('panorama/admin_ban_popup.res');
		var defaultSelected = config[type]['default'];

		$('#reasons').RemoveAllOptions();
		$('#reasons').RemoveAndDeleteChildren();
		Object.entries(config[type]['reasons']).forEach(([name]) => {
			var optionLabel = $.CreatePanel('Label', $('#reasons'), name, { text: name });
			$('#reasons').AddOption(optionLabel);
		});
		$('#reasons').SetSelected(Object.keys(defaultSelected)[0]);
		$('#times').SetSelected(defaultSelected[Object.keys(defaultSelected)[0]]);
	}

	var _Submit = function ()
	{
		var xuid = $.GetContextPanel().GetAttributeString( "xuid", "" );
		var rconMode = $.GetContextPanel().GetAttributeString( "rconmode", "" );
		var userID = 0;
		var time = $('#times').GetSelected().id;
		var reason = $('#reasons').GetSelected().id;
		var type = $('#types').GetSelected().id;
		var out_command = "";

		for (let i = 0; i < 10000; i++) {
			if(GameStateAPI.GetPlayerXuidFromUserID( i ) == xuid)
				userID = i;
		}

		var out_command = `sm_${type} #${userID} ${time} "${reason}"`;

		if(rconMode == 'true') out_command = `rcon `+out_command;

		GameInterfaceAPI.ConsoleCommand( out_command );

		$.DispatchEvent( 'UIPopupButtonClicked', '' );
	}

	return {
		Init : _Init,
		Submit : _Submit,
		OnTypeChange: _OnTypeChange
	};
})();