'use strict';

var contextmenuPlayerCard = ( function () {

	var _m_isScoreboard = false;
	var elNameLabel = '';
	var isRCONMode = false;
	var cl_adminpanel = GameInterfaceAPI.GetSettingString( "admin_panel" );
	var userID;

	var _Init = function ()
	{
		_m_isScoreboard = ( $.GetContextPanel().GetAttributeString( 'scoreboard', 'false' ) === 'true' ) ? true : false;
		//_m_isScoreboard = true;
		
		_LoadPlayerCard();
		_GetContextMenuEnteries();

		_InitRconMode();
		if(_m_isScoreboard && cl_adminpanel >= 1) {
			_LoadAdv();
		}
	};

	var _ChangeRconMode = function()
	{
		isRCONMode = $.GetContextPanel().FindChildInLayoutFile( 'JsToggleRCON' ).checked;
		var outnum = isRCONMode ? 1 : 0;

		GameInterfaceAPI.SetSettingString( "admin_rcon", outnum );
	};

	var _InitRconMode = function()
	{
		if( !_m_isScoreboard || cl_adminpanel <= 0 ) return;
		isRCONMode = GameInterfaceAPI.GetSettingString( 'admin_rcon' ) == '1' ? true : false;
		var button = $.GetContextPanel().FindChildInLayoutFile( 'JsToggleRCON' );
		button.checked = isRCONMode;
	};

	var _LoadPlayerCard = function( xuid )
	{
		var xuid = $.GetContextPanel().GetAttributeString( "xuid", "(not found)" );
		var newPanel = $.GetContextPanel().FindChildInLayoutFile( 'JsContextMenuPlayercard' );
		elNameLabel = FriendsListAPI.GetFriendName( xuid );

		if( newPanel )
			newPanel.DeleteAsync( .0 );

		var newPanel = $.CreatePanel('Panel', $.GetContextPanel().FindChildInLayoutFile('JsContextMenuSections'), 'JsContextMenuPlayercard' ); 
		newPanel.SetAttributeString( "xuid", xuid );
		newPanel.SetAttributeString( "scoreboard", _m_isScoreboard );
		newPanel.BLoadLayout('file://{resources}/layout/playercard.xml', false, false);
		
		userID = _GetUserID(xuid);
	};

	var _ContextMenus = [
		{
			name: 'invite',
			icon: 'invite',
			AvailableForItem: function ( id ) {
				return !GameStateAPI.IsLocalPlayerPlayingMatch() && !( LobbyAPI.IsPartyMember( id ) ) && !_IsSelf( id) &&
					( PartyListAPI.GetFriendPrimeEligible( MyPersonaAPI.GetXuid() ) || ( FriendsListAPI.GetFriendRelationship( id ) === "friend" ) ) &&
					( 'purchased' === MyPersonaAPI.GetLicenseType() );
			},
			OnSelected:  function ( id, type ) {
				FriendsListAPI.ActionInviteFriend( id, '' );
				$.DispatchEvent( 'ContextMenuEvent', '' );
				$.DispatchEvent( 'FriendInvitedFromContextMenu', id ); 
			} 
		},
		{
			name: 'join',
			icon: 'JoinPlayer',
			AvailableForItem: function ( id ) {
				if( FriendsListAPI.IsFriendJoinable( id ))
				{
					if ( GameStateAPI.IsPlayerConnected( id ) )
						return false;
					
					if (LobbyAPI.IsSessionActive()) {
						var party = LobbyAPI.GetSessionSettings().members;

						for (var i = 0; i < party.numPlayers; i++) {
							if ( id === party['machine' + i].player0.xuid )
								return false;
						}
					}

					return ( 'purchased' === MyPersonaAPI.GetLicenseType() );
				}
			},
			OnSelected:  function ( id ) {
				FriendsListAPI.ActionJoinFriendSession( id );
				$.DispatchEvent( 'ContextMenuEvent', '' );
			}
		},
		{
			name: 'steamprofile',
			icon: 'profile',
			AvailableForItem: function ( id ) {
				return 	MyPersonaAPI.GetLauncherType() !== "perfectworld";
				
			},
			OnSelected:  function ( id ) {
				SteamOverlayAPI.ShowUserProfilePage( id );
				$.DispatchEvent( 'ContextMenuEvent', '' );
			}
		},
		{
			name: 'kick_from_lobby',
			icon: 'friendignore',
			AvailableForItem: function( id )
			{
				if ( GameStateAPI.IsLocalPlayerPlayingMatch() )
					return false;
				
				if (LobbyAPI.IsSessionActive() && LobbyAPI.BIsHost()) {
					var party = LobbyAPI.GetSessionSettings().members;

					for (var i = 0; i < party.numPlayers; i++) {
						if (id === party['machine' + i].player0.xuid && !_IsSelf( id ))
							return true;
					}

				}
			},
			OnSelected:  function ( id ) {
				LobbyAPI.KickPlayer( id );
				$.DispatchEvent( 'ContextMenuEvent', '' );
			}
		},
		{
			name: 'leave_lobby',
			icon: 'leave',
			AvailableForItem: function ( id ) {
				if( !GameStateAPI.IsLocalPlayerPlayingMatch() && _IsSelf( id ) && LobbyAPI.IsSessionActive() )
				{
					var party = LobbyAPI.GetSessionSettings().members;
					return party.numPlayers > 1 ? true : false;
				}

				return false;
			},
			OnSelected:  function ( id ) {
				LobbyAPI.CloseSession();
				$.DispatchEvent( 'ContextMenuEvent', '' );
			}
		},
		{
			name: 'message',
			icon: 'message',
			AvailableForItem: function ( id ) {
				return !_IsSelf( id );
			},
			OnSelected:  function ( id ) {
				SteamOverlayAPI.StartChatWithUser( id );
				$.DispatchEvent( 'ContextMenuEvent', '' );
			}
		},
		{
			name: 'friendaccept',
			icon: 'friendaccept',
			AvailableForItem: function ( id ) {
				return FriendsListAPI.GetFriendStatusBucket( id ) === 'AwaitingLocalAccept';
			},
			OnSelected:  function ( id ) {
				SteamOverlayAPI.InteractWithUser( id, 'friendrequestaccept' );
				$.DispatchEvent( 'ContextMenuEvent', '' );
			}
		},
		{
			name: 'friendignore',
			icon: 'friendignore',
			AvailableForItem: function ( id ) {
				return FriendsListAPI.GetFriendStatusBucket( id ) === 'AwaitingLocalAccept';
			},
			OnSelected:  function ( id ) {
				SteamOverlayAPI.InteractWithUser( id, 'friendrequestignore' );
				$.DispatchEvent( 'ContextMenuEvent', '' );
			}
		},
		{
			name: 'cancelinvite',
			icon: 'friendignore',
			AvailableForItem: function ( id ) {
				return FriendsListAPI.GetFriendStatusBucket( id ) === 'AwaitingRemoteAccept';
			},
			OnSelected:  function ( id ) {
				SteamOverlayAPI.InteractWithUser( id, 'friendremove' );
				$.DispatchEvent( 'ContextMenuEvent', '' );
			}
		},
		{
			name: 'removefriend',
			icon: 'friendremove',
			AvailableForItem: function ( id ) {
				if( MyPersonaAPI.GetLauncherType() === "perfectworld" )
				{
					if ( _IsSelf( id ) ) return false;
					var status = FriendsListAPI.GetFriendStatusBucket( id );
					return status !== 'AwaitingRemoteAccept' && status !== 'AwaitingLocalAccept';
				}

				return false;
			},
			OnSelected:  function ( id ) {
				SteamOverlayAPI.InteractWithUser( id, 'friendremove' );
				$.DispatchEvent( 'ContextMenuEvent', '' );
			}
		},
		{
			name: 'request',
			icon: 'addplayer',
			AvailableForItem: function ( id ) {
				var status = FriendsListAPI.GetFriendStatusBucket( id );
				var isRequest = status === 'AwaitingRemoteAccept' || status === 'AwaitingLocalAccept';
				
				return FriendsListAPI.GetFriendRelationship( id ) !== "friend" && !_IsSelf( id ) && !isRequest;
			},
			OnSelected:  function ( id ) {
				SteamOverlayAPI.InteractWithUser( id, 'friendadd' );
				$.DispatchEvent( 'ContextMenuEvent', '' );
			}
		},
		{
			name: 'editprofile',
			icon: 'edit',
			AvailableForItem: function ( id ) {
				return _IsSelf( id );
			},
			OnSelected:  function ( id ) {
				var appID = SteamOverlayAPI.GetAppID();
				var communityUrl = SteamOverlayAPI.GetSteamCommunityURL();
				SteamOverlayAPI.OpenURL( communityUrl+"/profiles/"+id+"/minimaledit" );
				$.DispatchEvent( 'ContextMenuEvent', '' );
			}
		},
		{
			name: 'changecolor',
			icon: 'colorwheel',
			AvailableForItem: function ( id ) {
				return !GameStateAPI.IsLocalPlayerPlayingMatch() &&
					LobbyAPI.IsSessionActive() &&
					_IsSelf( id );
			},
			OnSelected: function ( id ) {
				LobbyAPI.ChangeTeammateColor();
			}
		},
		{
			name: 'mute',
			xml: 'file://{resources}/layout/mute_spinner.xml',
			icon: null,
			AvailableForItem: function ( id ) {
				return GameStateAPI.IsLocalPlayerPlayingMatch() && 
					!_IsSelf( id ) && 
					GameStateAPI.IsPlayerConnected( id );
			},
			OnSelected: null
		},
		{
			name: 'borrowmusickit',
			icon: 'music_kit',
			AvailableForItem: function ( id )
			{
				var borrowedPlayerIndex = parseInt( GameInterfaceAPI.GetSettingString( "cl_borrow_music_from_player_index" ) );
				return GameStateAPI.IsLocalPlayerPlayingMatch() &&
					!_IsSelf( id ) &&
					borrowedPlayerIndex !== GameStateAPI.GetPlayerIndex( id ) &&
					_HasMusicKit( id ) &&
					GameStateAPI.IsPlayerConnected( id );
			},
			OnSelected: function( id )
			{
				GameInterfaceAPI.SetSettingString( "cl_borrow_music_from_player_index", "" + GameStateAPI.GetPlayerIndex( id ) );
				$.DispatchEvent( 'ContextMenuEvent', '' );
			}
		},
		{
			name: 'stopborrowmusickit',
			icon: 'no_musickit',
			AvailableForItem: function ( id )
			{
				var borrowedPlayerIndex = parseInt( GameInterfaceAPI.GetSettingString( "cl_borrow_music_from_player_index" ) );
				if ( borrowedPlayerIndex === 0 )
					return false;

				return GameStateAPI.IsLocalPlayerPlayingMatch() &&
					(	( _IsSelf( id ) && borrowedPlayerIndex !== 0 ) ||
						( borrowedPlayerIndex === GameStateAPI.GetPlayerIndex( id ) ) ) &&
					GameStateAPI.IsPlayerConnected( id );
			},
			OnSelected: function( id )
			{
				$.DispatchEvent('Scoreboard_UnborrowMusicKit');
				$.DispatchEvent( 'ContextMenuEvent', '' );
			}
		},		
		{
			name: 'copycrosshair',
			icon: 'crosshair',
			AvailableForItem: function ( id ) {
				return GameStateAPI.IsLocalPlayerPlayingMatch() && 
					!_IsSelf( id ) && 
					GameStateAPI.IsPlayerConnected( id );
			},
			OnSelected: function( xuid )
			{
				$.DispatchEvent( 'Scoreboard_ApplyPlayerCrosshairCode', xuid ); 
				$.DispatchEvent( 'ContextMenuEvent', '' );
			}
		},
		{
			name: 'JsToggleRCON',
			icon: 'button',
			AvailableForItem: function ( id ) {
				return _m_isScoreboard && cl_adminpanel >= 1;
			},
			OnSelected:  function ( id ) {
				_ChangeRconMode();
			}
		},
	];

	var _ContextMenusAdmin = [
		{
			name: 'ban',
			png: 'false',
			icon: 'votekick',
			customname: 'Выдать наказание',
			func: function(xuid, rconEnabled) {
				UiToolkitAPI.ShowCustomLayoutPopupParameters('', 'file://{resources}/layout/csgool/popup_ban_player.xml', 'xuid=' + xuid + '&rconmode=' + rconEnabled + '&type=ban' );
			}
		},
		{
			name: 'cheats_check',
			png: 'false',
			icon: 'stream',
			customname: 'Вызвать на проверку',
			func: function(xuid) {
				contextmenuPlayerCard.AdvPlayer("sm_cc #%d", undefined, xuid);
			}
		},
		{
			name: 'copy_nick',
			png: 'false',
			icon: 'make_copy',
			customname: 'Скопировать ник',
			func: function(xuid) {
				SteamOverlayAPI.CopyTextToClipboard(GameStateAPI.GetPlayerName(xuid));
			}
		},
		{
			name: 'copy_steamid',
			png: 'false',
			icon: 'make_copy',
			customname: 'Скопировать SteamID',
			func: function(xuid) {
				SteamOverlayAPI.CopyTextToClipboard(xuid);
			}
		},
	];

	function _GetUserID(xuid) {
		if(!GameStateAPI.IsConnectedOrConnectingToServer())
			return 'not in match';

		for (let i = 0; i < 5000; i++) {
			if(GameStateAPI.GetPlayerXuidFromUserID( i ) === xuid)
				return i;
		}
		return "unknown";
	}

	var _HasMusicKit = function( id )
	{
		return ( InventoryAPI.GetMusicIDForPlayer( id ) > 1 );
	};

	var _IsSelf = function ( id )
	{
		return id === MyPersonaAPI.GetXuid();
	};

	var _GetContextMenuEnteries = function ()
	{
		$.CreatePanel('Panel', $.GetContextPanel(), '', { class: 'context-menu-playercard-seperator' } );
		var elContextMenuBtns = $.CreatePanel('Panel', $.GetContextPanel(), 'JsContextMenuPlayercardBtns', { class: 'context-menu-playercard-btns' } );

		var xuid = $.GetContextPanel().GetAttributeString( "xuid", "(not found)" );
		var type = $.GetContextPanel().GetAttributeString( "type", "" );

		elContextMenuBtns.xuid = xuid;

		_ContextMenus.forEach( function( entry ) {
			if ( entry.AvailableForItem( xuid )) 
			{
				var elEntryBtn;

				if(entry.icon === "button") {

					elEntryBtn = $.CreatePanel( 'ToggleButton', elContextMenuBtns, entry.name, { 
						class: 'PopupButton',
						style: 'tooltip-position: bottom;'
					} );

					$.CreatePanel( 'Image', elEntryBtn, entry.name, {} );
	
					elEntryBtn.SetPanelEvent( 'onactivate', entry.OnSelected.bind( this, xuid, type ) );
					elEntryBtn.SetPanelEvent( 'onmouseover', _OnMouseOver.bind(this, elEntryBtn.id, 'RCON режим (требует RCON пароль)') );
					elEntryBtn.SetPanelEvent( 'onmouseout', _OnMouseOut );

				} else if ( 'xml' in entry ) {

					elEntryBtn = $.CreatePanel( 'Panel', elContextMenuBtns, entry.name, { 
						class: 'IconButton',
						style: 'tooltip-position: bottom;'
					} );

					elEntryBtn.BLoadLayout( entry.xml, false, false );

				} else {

					elEntryBtn = $.CreatePanel( 'Button', elContextMenuBtns, entry.name, { 
						class: 'IconButton',
						style: 'tooltip-position: bottom;'
					} );

					$.CreatePanel( 'Image', elEntryBtn, entry.name, { src: 'file://{images}/icons/ui/' + entry.icon + '.svg' } );

					elEntryBtn.SetPanelEvent( 'onactivate', entry.OnSelected.bind( this, xuid, type ) );

					var OnMouseOver = function ()
					{
						UiToolkitAPI.ShowTextTooltip( elEntryBtn.id, '#tooltip_' + entry.name );
					}

					elEntryBtn.SetPanelEvent('onmouseover', OnMouseOver );
					elEntryBtn.SetPanelEvent('onmouseout', _OnMouseOut );

				}
			}
		});
	};

	var _LoadAdv = function () {
		$.CreatePanel('Panel', $.GetContextPanel(), '', { class: 'context-menu-playercard-seperator' } );
		var xuid = $.GetContextPanel().GetAttributeString( "xuid", "(not found)" );
		var elContextMenuBtnsBans = $.CreatePanel('Panel', $.GetContextPanel(), 'JsContextMenuPlayercardBtnsBans', { class: 'context-menu-playercard-btns' } );
		elContextMenuBtnsBans.xuid = xuid;

		_ContextMenusAdmin.forEach( function( entry ) {
			var elEntryBtn;

			elEntryBtn = $.CreatePanel( 'Button', elContextMenuBtnsBans, entry.name, { 
				class: 'IconButton',
				style: 'tooltip-position: bottom;'
			} );

			if(entry.png == 'true')
				$.CreatePanel( 'Image', elEntryBtn, entry.name, { src: 'file://{resources}/png/' + entry.icon } );
			else if(entry.png == 'false')
				$.CreatePanel( 'Image', elEntryBtn, entry.name, { src: 'file://{images}/icons/ui/' + entry.icon + '.svg' } );
			
			elEntryBtn.SetPanelEvent('onactivate', _BanMutePlayer.bind(this, xuid, entry.func));
			elEntryBtn.SetPanelEvent('onmouseover', _OnMouseOver.bind(this, elEntryBtn.id, entry.customname) );
			elEntryBtn.SetPanelEvent('onmouseout', _OnMouseOut );
		});

		var adv = $.LoadKeyValuesFile('panorama/admin_buttons.res');
		Object.entries(adv).forEach(([key]) => {
			if( adv[key].cvar_level <= cl_adminpanel ) {
				var addToClass = Object.entries(adv[key]).length > 8 ? 'vscroll' : ''
				var elContextMenuBtns = $.CreatePanel('Panel', $.GetContextPanel(), 'JsContextMenuPlayercardBtns'+key, { class: 'context-menu-playercard-btns '+addToClass, style: 'max-height: 400px;' } );
				elContextMenuBtns.xuid = xuid;
				Object.entries(adv[key]).forEach(([key, value]) => {
					if(key != 'cvar_level') {
						var elEntryBtn;

						elEntryBtn = $.CreatePanel( 'Button', elContextMenuBtns, key, { 
							class: 'IconButton',
							style: 'tooltip-position: bottom;'
						} );

						if(value.custom_image == 'true')
							$.CreatePanel( 'Image', elEntryBtn, key, { src: 'file://{resources}/png/' + value.icon } );
						else if(value.custom_image == 'false')
							$.CreatePanel( 'Image', elEntryBtn, key, { src: 'file://{images}/icons/ui/' + value.icon + '.svg' } );

						elEntryBtn.SetPanelEvent('onactivate', _AdvPlayer.bind( this, value.command ));
						elEntryBtn.SetPanelEvent('onmouseover', _OnMouseOver.bind(this, elEntryBtn.id, value.name) );
						elEntryBtn.SetPanelEvent('onmouseout', _OnMouseOut );
					}
					
				});
			}
			
		});
	}

	var _BanMutePlayer = function ( xuid, func ) {
		func(xuid, isRCONMode);
	};

	var _AdvPlayer = function ( command ) {
		var out_command = command.replace("%d", userID);

		if(!isRCONMode) GameInterfaceAPI.ConsoleCommand( out_command );
		else GameInterfaceAPI.ConsoleCommand( "rcon "+out_command );
	};

	var _OnMouseOver = function ( id, name )
	{
		UiToolkitAPI.ShowTextTooltip( id, name );
	}

	var _OnMouseOut = function ()
	{
		UiToolkitAPI.HideTextTooltip();
	}

	return {
		Init: _Init,
		AdvPlayer: _AdvPlayer,
	};

})();
(function(){
})();