summaryrefslogtreecommitdiff
path: root/game/client/tf/tf_consumables.cpp
blob: 3508b8b2f0dec1b8834dc42b147d49339338f055 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: 
//
// $NoKeywords: $
//=============================================================================
#include "cbase.h"

// for messaging with the GC
#include "econ_gcmessages.h"
#include "econ_item_inventory.h"
#include "tf_gcmessages.h"
#include "tf_duel_summary.h"
#include "gc_clientsystem.h"

// other
#include "c_playerresource.h"
#include "c_tf_player.h"
#include "tf_item_wearable.h"
#include "econ_notifications.h"
#include "tf_hud_chat.h"
#include "c_tf_gamestats.h"
#include "tf_gamerules.h"
#include "tf_item_tools.h"
#include "c_tf_freeaccount.h"
#include "tf_item_powerup_bottle.h"
#include "tf_weapon_grapplinghook.h"

// for UI
#include "clientmode_tf.h"
#include "confirm_dialog.h"
#include "select_player_dialog.h"
#include "econ_notifications.h"
#include "vgui/ISurface.h"
#include "vgui/character_info_panel.h"
#include "tf_hud_mainmenuoverride.h"
#include "econ_ui.h"
#include "backpack_panel.h"
#include "store/v1/tf_store_page.h"
#include "econ_item_description.h"
#include "weapon_selection.h"

// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>

//-----------------------------------------------------------------------------
// Wrapped Gift Declarations

void UseGift( CEconItemView* pItem, CSteamID targetID );
extern void PerformToolAction_UnwrapGift( vgui::Panel* pParent, CEconItemView *pGiftItem );
extern void ShowWaitingDialog( CGenericWaitingDialog *pWaitingDialog, const char* pUpdateText, bool bAnimate, bool bShowCancel, float flMaxDuration );
class CDeliverGiftSelectDialog;
CDeliverGiftSelectDialog *OpenDeliverGiftDialog( vgui::Panel *pParent, CEconItemView *pItem );
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Duel Declarations
bool DuelMiniGame_IsDuelingLocalPlayer( C_TFPlayer *pPlayer );
bool DuelMiniGame_IsDueling();
//-----------------------------------------------------------------------------

class CWaitForPackageDialog : public CGenericWaitingDialog
{
public:
	CWaitForPackageDialog( vgui::Panel *pParent ) : CGenericWaitingDialog( pParent )
	{
	}

protected:
	virtual void OnTimeout()
	{
		// Play an exciting sound!
		vgui::surface()->PlaySound( "misc/achievement_earned.wav" );

		// Show them their loot!
		InventoryManager()->ShowItemsPickedUp( true );
	}
};

bool IgnoreRequestFromUser( const CSteamID &steamID )
{
	// ignore blocked players
	if ( steamapicontext && steamapicontext->SteamFriends() )
	{
		EFriendRelationship eRelationship = steamapicontext->SteamFriends()->GetFriendRelationship( steamID );
		switch ( eRelationship )
		{
			case k_EFriendRelationshipBlocked:
			{
				return true;
			}
		}
	}
	return false;
}

static void ShowSelectDuelTargetDialog( uint64 iItemID );

enum EServerPlayersGCSend
{
	kServerPlayers_DontSend,
	kServerPlayers_Send,
};

struct CUseItemConfirmContext
{
public:
	CUseItemConfirmContext( CEconItemView *pEconItemView, EServerPlayersGCSend eSendServerPlayers, const char* pszConfirmUseSound = NULL )
		: m_pEconItemView( pEconItemView )
		, m_bSendServerPlayers( eSendServerPlayers == kServerPlayers_Send )
		, m_pszConfirmUseSound( pszConfirmUseSound )
	{
		Assert( eSendServerPlayers == kServerPlayers_DontSend || eSendServerPlayers == kServerPlayers_Send );
	}

	void OnConfirmUse()
	{
		if ( m_pszConfirmUseSound && *m_pszConfirmUseSound )
		{
			vgui::surface()->PlaySound( m_pszConfirmUseSound );
		}
	}

	const char* m_pszConfirmUseSound;
	CEconItemView *m_pEconItemView;
	bool m_bSendServerPlayers;
};

static void UseItemConfirm( bool bConfirmed, void *pContext )
{
	static CSchemaAttributeDefHandle pAttrDef_UnlimitedUse( "unlimited quantity" );

	CUseItemConfirmContext *pConfirmContext = (CUseItemConfirmContext *)pContext;
	CEconItemView *pEconItemView = pConfirmContext->m_pEconItemView;

	if ( bConfirmed )
	{
		pConfirmContext->OnConfirmUse();

		if ( pEconItemView && !pEconItemView->FindAttribute( pAttrDef_UnlimitedUse ) )
		{
			GCSDK::CProtoBufMsg<CMsgUseItem> msg( k_EMsgGCUseItemRequest );
			msg.Body().set_item_id( pConfirmContext->m_pEconItemView->GetItemID() );

			if ( pConfirmContext->m_bSendServerPlayers )
			{
				for ( int i = 1; i <= gpGlobals->maxClients; i++ )
				{
					CBasePlayer *pPlayer = UTIL_PlayerByIndex( i );
					if ( pPlayer == NULL )
						continue;

					CSteamID steamIDPlayer;
					if ( !pPlayer->GetSteamID( &steamIDPlayer ) )
						continue;

					msg.Body().add_gift__potential_targets( steamIDPlayer.GetAccountID() );
				}
			}

			GCClientSystem()->BSendMessage( msg );
		}

		EconUI()->Gamestats_ItemTransaction( IE_ITEM_USED_CONSUMABLE, pEconItemView, NULL );

		// CBaseHudChat *pHUDChat = (CBaseHudChat *)GET_HUDELEMENT( CHudChat );
		// if ( pHUDChat )
		// {
		// 	char szAnsi[1024];
		// 	Q_snprintf( szAnsi, 1024, "Using item: %ull", pItem->GetItemID() );
		// 	pHUDChat->Printf( CHAT_FILTER_NONE, "%s", szAnsi );
		// }
	}
	delete pConfirmContext;
}

static void OpenPass( bool bConfirmed, void *pContext )
{
	if ( bConfirmed )
	{
		vgui::surface()->PlaySound( "ui/item_gift_wrap_unwrap.wav" );
		ShowWaitingDialog( new CWaitForPackageDialog( NULL ), "#ToolRedeemingPass", true, false, 5.0f );
	}
	UseItemConfirm( bConfirmed, pContext );
}

static void PrintTextToChat( const char *pText, KeyValues *pKeyValues )
{
	GetClientModeTFNormal()->PrintTextToChat( pText, pKeyValues );
}

void GetPlayerNameBySteamID( const CSteamID &steamID, OUT_Z_CAP(maxLenInChars) char *pDestBuffer, int maxLenInChars )
{
	// always attempt to precache this user's name -- we may need it later after they leave the server, for instance,
	// even if that's where they are now
	InventoryManager()->PersonaName_Precache( steamID.GetAccountID() );

	// first, look through players on our connected gameserver if available -- we already have this information and
	// if there's a disagreement between Steam and the gameserver the gameserver view is what the player is probably
	// expecting anyway
	if ( engine->IsInGame() )
	{
		for( int iPlayerIndex = 1 ; iPlayerIndex <= MAX_PLAYERS; iPlayerIndex++ )
		{
			if ( g_PR->IsConnected( iPlayerIndex ) )
			{
				player_info_t pi;
				if ( !engine->GetPlayerInfo( iPlayerIndex, &pi ) )
					continue;
				if ( !pi.friendsID )
					continue;

				CSteamID steamIDTemp( pi.friendsID, 1, GetUniverse(), k_EAccountTypeIndividual );
				if ( steamIDTemp == steamID )
				{
					V_strncpy( pDestBuffer, pi.name, maxLenInChars );
					return;
				}
			}
		}
	}

	// try the persona name cache
	// this goes to steam if necessary
	const char *pszName = InventoryManager()->PersonaName_Get( steamID.GetAccountID() );
	if ( pszName != NULL )
	{
		V_strncpy( pDestBuffer, pszName, maxLenInChars );
		return;
	}

	// otherwise, return what we would normally return
	V_strncpy( pDestBuffer, steamapicontext->SteamFriends()->GetFriendPersonaName( steamID ), maxLenInChars );
}

static bool IsGCUseableItem( const GameItemDefinition_t *pItemDef )
{
	Assert( pItemDef );

	return (pItemDef->GetCapabilities() & ITEM_CAP_USABLE_GC) != 0;
}

//-----------------------------------------------------------------------------
// Purpose: Implementation of the local response for someone who used a dueling minigame
//-----------------------------------------------------------------------------
void CEconTool_DuelingMinigame::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	Assert( pItem );

	C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
	Assert( pLocalPlayer );

	if ( DuelMiniGame_IsDueling() )
	{
		// can't duel if already dueling
		ShowMessageBox( "#TF_Duel_Title",  "#TF_Duel_InADuel_Initiator", "#GameUI_OK" );
		return;
	}
	if ( pLocalPlayer->GetTeamNumber() != TF_TEAM_RED && pLocalPlayer->GetTeamNumber() != TF_TEAM_BLUE )
	{
		// can't duel from spectator mode, etc.
		ShowMessageBox( "#TF_UseFail_NotOnTeam_Title",  "#TF_UseFail_NotOnTeam", "#GameUI_OK" );
		return;
	}
	if ( TFGameRules() && !TFGameRules()->CanInitiateDuels() )
	{
		ShowMessageBox( "#TF_Duel_Title",  "#TF_Duel_CannotUse", "#GameUI_OK" );
		return;
	}

	ShowSelectDuelTargetDialog( pItem->GetItemID() );
}

//-----------------------------------------------------------------------------
// Purpose: Implementation of the local response for someone who used a noisemaker
//-----------------------------------------------------------------------------
void CEconTool_Noisemaker::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	Assert( pItem );

	C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
	Assert( pLocalPlayer );

	if ( gpGlobals->curtime < pLocalPlayer->m_Shared.GetNextNoiseMakerTime() )
		return;

	if ( !pLocalPlayer->IsAlive() )
		return;

	if ( pLocalPlayer->GetTeamNumber() < FIRST_GAME_TEAM ) 
		return;

	// This may not be ideal. We're going to have the game server do the noise effect,
	// without checking the GC to see whether we have charges available. Querying the
	// GC would cause a significant delay before the item was used, so we simulate.

	// Tell the game server to play the sound.
	KeyValues *kv = new KeyValues( "use_action_slot_item_server" );
	engine->ServerCmdKeyValues( kv );

	// Tell the GC to consume a charge.
	CUseItemConfirmContext *context = new CUseItemConfirmContext( pItem, kServerPlayers_DontSend );
	UseItemConfirm( true, context );

	// Notify the player that they used their last charge.
	if ( pItem->GetItemQuantity() <= 1 )
	{
		CEconNotification *pNotification = new CEconNotification();
		pNotification->SetText( "#TF_NoiseMaker_Exhausted" );
		pNotification->SetLifetime( 7.0f );
		NotificationQueue_Add( pNotification );
	}
}

//-----------------------------------------------------------------------------
// Purpose: Implementation of the local response for someone who used a gift-wrapped item
//-----------------------------------------------------------------------------
void UseUntargetedGiftConfirm( bool bConfirmed, void *pContext )
{
	if ( bConfirmed )
	{
		UseGift( static_cast<CEconItemView *>( pContext ), k_steamIDNil );
	}
}

void CEconTool_WrappedGift::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	Assert( pItem );

	if ( BIsDirectGift() )
	{
		OpenDeliverGiftDialog( pParent, pItem );
	}
	else
	{
		// ...otherwise, we should try and open the gift!
		PerformToolAction_UnwrapGift( pParent, pItem );
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CEconTool_WeddingRing::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	Assert( pItem );

	// Don't do anything if we haven't been gifted already -- we don't expect to
	// ever get in here, really.
	static CSchemaAttributeDefHandle pAttrDef_GifterAccountID( "gifter account id" );

	uint32 unAccountID;
	if ( !pItem->FindAttribute( pAttrDef_GifterAccountID, &unAccountID ) )
		return;

	// We have been gifted, so pop up a dialog box to allow the user to accept/reject
	// the proposal.
	CTFGenericConfirmDialog *pDialog = ShowConfirmDialog( "#TF_UseWeddingRing_Title", "#TF_UseWeddingRing_Text", 
														  "#TF_WeddingRing_AcceptProposal", "#TF_WeddingRing_RejectProposal", 
														  &UseItemConfirm );

	pDialog->AddStringToken( "item_name", pItem->GetItemName() );

	CUtlConstWideString sProposerPersonaName;
	GLocalizationProvider()->ConvertUTF8ToLocchar( TFInventoryManager()->PersonaName_Get( unAccountID ), &sProposerPersonaName );
	pDialog->AddStringToken( "proposer_name", sProposerPersonaName.Get() );

	pDialog->SetContext( new CUseItemConfirmContext( pItem, kServerPlayers_DontSend ) );
}

//-----------------------------------------------------------------------------
// Purpose: Implementation of the local response for someone who used a backpack expander
//-----------------------------------------------------------------------------
void CEconTool_BackpackExpander::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	Assert( pItem );

	// first validate that they aren't already at max inventory size and can use the item
	uint32 unExtraSlots =GetBackpackSlots();
	if ( unExtraSlots == 0 )
	{
		return;
	}
	uint32 unNewNumSlots = TFInventoryManager()->GetLocalTFInventory()->GetMaxItemCount() + unExtraSlots;
	if ( unNewNumSlots > MAX_NUM_BACKPACK_SLOTS )
	{
		ShowMessageBox( "#TF_UseBackpackExpanderFail_Title",  "#TF_UseBackpackExpanderFail_Text", "#GameUI_OK" );
		return;
	}
	// Free Trials can use expanders but max out at a smaller value since premium gains a bunch of free slots
	if ( IsFreeTrialAccount() && unNewNumSlots > MAX_NUM_BACKPACK_SLOTS - (DEFAULT_NUM_BACKPACK_SLOTS - DEFAULT_NUM_BACKPACK_SLOTS_FREE_TRIAL_ACCOUNT) )
	{
		ShowMessageBox( "#TF_UseBackpackExpanderFail_Title",  "#TF_UseBackpackExpanderFail_Text", "#GameUI_OK" );
		return;
	}
	
	CTFGenericConfirmDialog *pDialog = ShowConfirmDialog( "#TF_UseBackpackExpander_Title", "#TF_UseBackpackExpander_Text", 
														  "#GameUI_OK", "#Cancel", 
														  &UseItemConfirm );
	pDialog->AddStringToken( "item_name", pItem->GetItemName() );
	wchar_t wszUsesLeft[32];
	_snwprintf( wszUsesLeft, ARRAYSIZE(wszUsesLeft), L"%d", pItem->GetItemQuantity() );
	pDialog->AddStringToken( "uses_left", wszUsesLeft );
	wchar_t wszNewSize[32];
	_snwprintf( wszNewSize, ARRAYSIZE(wszNewSize), L"%d", unNewNumSlots );
	pDialog->AddStringToken( "new_size", wszNewSize );
	pDialog->SetContext( new CUseItemConfirmContext( pItem, kServerPlayers_DontSend ) );
}

//-----------------------------------------------------------------------------
// Purpose: Implementation of the local response for someone who used an account upgrade
//-----------------------------------------------------------------------------
void CEconTool_AccountUpgradeToPremium::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	Assert( pItem );

	// if the account is already premium, abort here
	if ( !IsFreeTrialAccount() )
	{
		ShowMessageBox( "#TF_UseAccountUpgradeToPremiumFail_Title",  "#TF_UseAccountUpgradeToPremiumFail_Text", "#GameUI_OK" );
		return;
	}

	// show a confirmation dialog to make sure they want to consume the charge
	CTFGenericConfirmDialog *pDialog = ShowConfirmDialog( "#TF_UseAccountUpgradeToPremium_Title", "#TF_UseAccountUpgradeToPremium_Text", 
														  "#GameUI_OK", "#Cancel", 
														  &UseItemConfirm );
	pDialog->AddStringToken( "item_name", pItem->GetItemName() );
	wchar_t wszUsesLeft[32];
	_snwprintf( wszUsesLeft, ARRAYSIZE(wszUsesLeft), L"%d", pItem->GetItemQuantity() );
	pDialog->AddStringToken( "uses_left", wszUsesLeft );
	pDialog->SetContext( new CUseItemConfirmContext( pItem, kServerPlayers_DontSend ) );
}

//-----------------------------------------------------------------------------
// Purpose: Implementation of the local response for someone who used a claim code item
//-----------------------------------------------------------------------------
void CEconTool_ClaimCode::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	Assert( pItem );

	CTFGenericConfirmDialog *pDialog = ShowConfirmDialog( "#TF_UseClaimCode_Title", "#TF_UseClaimCode_Text", 
														  "#GameUI_OK", "#Cancel", 
														  &UseItemConfirm );
	pDialog->AddStringToken( "item_name", pItem->GetItemName() );

	const char *pszClaimValue = GetClaimType();
	if ( pszClaimValue )
	{
		wchar_t wszClaimType[128];
		KeyValuesAD pkvDummy( "dummy" );
		g_pVGuiLocalize->ConstructString_safe( wszClaimType, pszClaimValue, pkvDummy );
		pDialog->AddStringToken( "claim_type", wszClaimType );
	}
	pDialog->SetContext( new CUseItemConfirmContext( pItem, kServerPlayers_DontSend ) );
}

//-----------------------------------------------------------------------------
// Purpose: Implementation of the local response for someone who used an item that doesn't have
//			special-case handling (ie., paint); called into from other code
//-----------------------------------------------------------------------------
static bool s_bConsumableToolOpeningGift = false;
static void ClientConsumableTool_Generic( CEconItemView *pItem, vgui::Panel *pParent )
{
	Assert( pItem );
	Assert( pItem->GetItemDefinition() );
	Assert( pItem->GetItemDefinition()->GetEconTool() );

	CTFGenericConfirmDialog *pDialog = ShowConfirmDialog( "#TF_UseItem_Title", "#TF_UseItem_Text", 
														  "#GameUI_OK", "#Cancel", 
														  &UseItemConfirm );
	pDialog->AddStringToken( "item_name", pItem->GetItemName() );
	wchar_t wszUsesLeft[32];
	_snwprintf( wszUsesLeft, ARRAYSIZE(wszUsesLeft), L"%d", pItem->GetItemQuantity() );
	pDialog->AddStringToken( "uses_left", wszUsesLeft );
	pDialog->SetContext(
		new CUseItemConfirmContext( pItem,
									pItem->GetItemDefinition()->GetTypedEconTool<CEconTool_Gift>()
										? kServerPlayers_Send
										: kServerPlayers_DontSend ) );

	// Minor Hack to get sound to play differently.  Add a look up table
	s_bConsumableToolOpeningGift = false;
	const CEconTool_Gift *pGiftTool = pItem->GetItemDefinition()->GetTypedEconTool<CEconTool_Gift>();
	if ( pGiftTool && pGiftTool->GetTargetRule() == kGiftTargetRule_OnlySelf)
	{
		s_bConsumableToolOpeningGift = true;
	}
}

//-----------------------------------------------------------------------------
// Purpose: Generic Response
//-----------------------------------------------------------------------------
void CEconTool_Xifier::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	ClientConsumableTool_Generic( pItem, pParent );
}

//-----------------------------------------------------------------------------
void CEconTool_ItemEaterRecharger::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	// Tell the GC to consume a charge.
	CUseItemConfirmContext *context = new CUseItemConfirmContext( pItem, kServerPlayers_DontSend );
	UseItemConfirm( true, context );
}

//-----------------------------------------------------------------------------
// Purpose: Implementation of the local response for someone who used (tried to redeem) a collection
//-----------------------------------------------------------------------------
void CEconTool_PaintCan::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	ClientConsumableTool_Generic( pItem, pParent );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CEconTool_Gift::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	ClientConsumableTool_Generic( pItem, pParent );
}

//-----------------------------------------------------------------------------
// Purpose: Implementation of the local response for someone who used (tried to redeem) a collection
//-----------------------------------------------------------------------------
void CEconTool_Default::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	ClientConsumableTool_Generic( pItem, pParent );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CEconTool_TFEventEnableHalloween::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	Assert( pItem );

	// Tell the GC we want to use this item.
	GCSDK::CProtoBufMsg<CMsgGC_Client_UseServerModificationItem> msg( k_EMsgGC_Client_UseServerModificationItem );
	msg.Body().set_item_id( pItem->GetItemID() );

	GCClientSystem()->BSendMessage( msg );
}

//-----------------------------------------------------------------------------
void CEconTool_DuckToken::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	ClientConsumableTool_Generic( pItem, pParent );
}
//-----------------------------------------------------------------------------
void CEconTool_GrantOperationPass::OnClientUseConsumable( CEconItemView *pItem, vgui::Panel *pParent ) const
{
	Assert( pItem );
	const CEconTool_GrantOperationPass *pEconToolOperationPass = pItem->GetItemDefinition()->GetTypedEconTool<CEconTool_GrantOperationPass>();
	if ( !pEconToolOperationPass )
	{
		ShowMessageBox( "#TF_UseOperationPassFail_Title", "#TF_UseOperationPassFail_Text", "#GameUI_OK" );
		return;
	}

	// Check that the player doesn't already have an active pass
	const char *szPassName = pEconToolOperationPass->m_pOperationPassName;
	CEconItemDefinition *pActivePassItemDef = GetItemSchema()->GetItemDefinitionByName( szPassName );
	CPlayerInventory *pLocalInv = TFInventoryManager()->GetLocalInventory();
	if ( !pLocalInv || !pActivePassItemDef  )
	{
		ShowMessageBox( "#TF_UseOperationPassFail_Title", "#TF_UseOperationPassFail_Text", "#GameUI_OK" );
		return;
	}

	for ( int i = 0; i < pLocalInv->GetItemCount(); ++i )
	{
		CEconItemView *pItemLocal = pLocalInv->GetItem( i );
		Assert( pItemLocal );
		if ( pItemLocal->GetItemDefinition() == pActivePassItemDef )
		{
			ShowMessageBox( "#TF_UseOperationPassAlreadyActive_Title", "#TF_UseOperationPassAlreadyActive_Text", "#GameUI_OK" );	
			return;
		}
	}

	vgui::surface()->PlaySound( "ui/quest_operation_pass_buy.wav" );

	const char *pszTitle = "#TF_UseOperationPass_Title";
	const char *pszBody = "#TF_UseOperationPass_Text";

	static CSchemaItemDefHandle pItemDef_InvasionPass( "Unused Invasion Pass" ); 
	if ( pItem->GetItemDefinition() == pItemDef_InvasionPass )
	{
		pszBody = "#TF_UseInvasionPass_Text";
	}

	// show a confirmation dialog to make sure they want to consume the charge
	CTFGenericConfirmDialog *pDialog = ShowConfirmDialog( pszTitle, pszBody,
		"#GameUI_OK", "#Cancel",
		&OpenPass );
	pDialog->AddStringToken( "item_name", pItem->GetItemName() );
	wchar_t wszUsesLeft[32];
	_snwprintf( wszUsesLeft, ARRAYSIZE( wszUsesLeft ), L"%d", pItem->GetItemQuantity() );
	pDialog->AddStringToken( "uses_left", wszUsesLeft );
	pDialog->SetContext( new CUseItemConfirmContext( pItem, kServerPlayers_DontSend, "ui/quest_operation_pass_use.wav" ) );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class CGCEventEnableResponse : public GCSDK::CGCClientJob
{
public:
	CGCEventEnableResponse( GCSDK::CGCClient *pClient ) : GCSDK::CGCClientJob( pClient ) {}
	virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
	{
		GCSDK::CProtoBufMsg<CMsgGC_Client_UseServerModificationItem_Response> msg( pNetPacket );

		switch ( msg.Body().response_code() )
		{
		case CMsgGC_Client_UseServerModificationItem_Response::kServerModificationItemResponse_AlreadyInUse:
			ShowMessageBox( "#TF_ServerEnchantmentType", "#TF_Eternaween__AlreadyInUse", (KeyValues *)NULL );
			break;

		case CMsgGC_Client_UseServerModificationItem_Response::kServerModificationItemResponse_NotOnAuthenticatedServer:
			ShowMessageBox( "#TF_ServerEnchantmentType", "#TF_Eternaween__AuthenticatedServerRequired", (KeyValues *)NULL );
			break;

		case CMsgGC_Client_UseServerModificationItem_Response::kServerModificationItemResponse_ServerReject:
			ShowMessageBox( "#TF_ServerEnchantmentType", "#TF_Eternaween__ServerReject", (KeyValues *)NULL );
			break;

		case CMsgGC_Client_UseServerModificationItem_Response::kServerModificationItemResponse_InternalError:
			ShowMessageBox( "#TF_ServerEnchantmentType", "#TF_Eternaween__InternalError", (KeyValues *)NULL );
			break;

		case CMsgGC_Client_UseServerModificationItem_Response::kServerModificationItemResponse_EventAlreadyActive:
			ShowMessageBox( "#TF_ServerEnchantmentType", "#TF_Eternaween__EventAlreadyActive", (KeyValues *)NULL );
			break;
		}
		
		return true;
	}
};
GC_REG_JOB( GCSDK::CGCClient, CGCEventEnableResponse, "CGCEventEnableResponse", k_EMsgGC_Client_UseServerModificationItem_Response, GCSDK::k_EServerTypeGCClient );

// invoked when the local player attempts to consume the given item
void UseConsumableItem( CEconItemView *pItem, vgui::Panel *pParent )
{
	Assert( pItem );

	C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();

	const GameItemDefinition_t *pItemDef = pItem->GetStaticData();
	Assert( pItemDef );

	bool bUsableOutOfGame = (pItemDef->GetCapabilities() & ITEM_CAP_USABLE_OUT_OF_GAME) != 0;

	// if we aren't useable outside of the game then make sure that we're in a game and that
	// we have a local player we can use
	if ( !bUsableOutOfGame )
	{
		if ( !engine->IsInGame() )
		{
			ShowMessageBox( "#TF_UseFail_NotInGame_Title",  "#TF_UseFail_NotInGame", "#GameUI_OK" );
			return;
		}

		if ( pLocalPlayer == NULL )
			return;
	}
	
	// make sure this item meets our baseline useable criteria
	if ( pItem->GetItemQuantity() <= 0 )
		return;

	if ( !IsGCUseableItem( pItemDef ) )
		return;

	const IEconTool *pEconTool = pItemDef->GetEconTool();
	if ( !pEconTool )
		return;

	// do whatever client work needs to be done, send a request to the GC to use the item, etc.
	pEconTool->OnClientUseConsumable( pItem, pParent );
}

// Called from the trade dialog when the player selects a target user ID.
void UseGift( CEconItemView* pItem, CSteamID targetID )
{
	// Validate pItem...
	if ( !pItem )
		return;

	const GameItemDefinition_t *pItemDef = pItem->GetItemDefinition();
	if ( !pItemDef )
		return;

	if ( !IsGCUseableItem( pItemDef ) )
		return;

	if ( !pItemDef->GetTypedEconTool<CEconTool_WrappedGift>() )
		return;

	GCSDK::CGCMsg< MsgGCDeliverGift_t > msg( k_EMsgGCDeliverGift );
	msg.Body().m_unGiftID = pItem->GetItemID();
	msg.Body().m_ulTargetSteamID = targetID.ConvertToUint64();
	GCClientSystem()->BSendMessage( msg );
																	  
	CSteamID steamID = steamapicontext->SteamUser()->GetSteamID();

	C_CTF_GameStats.Event_Trading( IE_TRADING_ITEM_GIFTED, pItem, true, 
		steamID.ConvertToUint64(), targetID.ConvertToUint64() );
}

class CDeliverGiftSelectDialog : public CSelectPlayerDialog
{
public:
	CDeliverGiftSelectDialog( vgui::Panel *parent );

	virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
	void SetItem( CEconItemView* pItem ) { m_pItem = pItem; }
	virtual bool AllowOutOfGameFriends() { return true; }

	virtual void OnSelectPlayer( const CSteamID &steamID )
	{
		UseGift( m_pItem, steamID );
	}

private:
	CEconItemView* m_pItem;
};

CDeliverGiftSelectDialog::CDeliverGiftSelectDialog( vgui::Panel *parent ) 
: CSelectPlayerDialog( parent )
{
}

void CDeliverGiftSelectDialog::ApplySchemeSettings( vgui::IScheme *pScheme )
{
	CSelectPlayerDialog::ApplySchemeSettings( pScheme );
	SetDialogVariable( "title", g_pVGuiLocalize->Find( "TF_DeliverGiftDialog_Title" ) );
}

static vgui::DHANDLE<CDeliverGiftSelectDialog> g_hDeliverGiftDialog;

CDeliverGiftSelectDialog *OpenDeliverGiftDialog( vgui::Panel *pParent, CEconItemView *pItem )
{
	if (!g_hDeliverGiftDialog.Get())
	{
		g_hDeliverGiftDialog = vgui::SETUP_PANEL( new CDeliverGiftSelectDialog( pParent ) );
	}
	g_hDeliverGiftDialog->InvalidateLayout( false, true );
	g_hDeliverGiftDialog->Reset();
	g_hDeliverGiftDialog->SetVisible( true );
	g_hDeliverGiftDialog->MakePopup();
	g_hDeliverGiftDialog->MoveToFront();
	g_hDeliverGiftDialog->SetKeyBoardInputEnabled(true);
	g_hDeliverGiftDialog->SetMouseInputEnabled(true);
	g_hDeliverGiftDialog->SetItem( pItem );
	TFModalStack()->PushModal( g_hDeliverGiftDialog );

	return g_hDeliverGiftDialog;
}

// This is the command the user will execute.
// We want this to happen on the client, before forwarding to the game server, since we don't trust
// the game server.
static bool g_bUsedGCItem = false;
static void StartUseActionSlotItem( const CCommand &args )
{
	if ( !engine->IsInGame() )
	{
		return;
	}

	C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
	if ( pLocalPlayer == NULL )
	{
		return;
	}

	pLocalPlayer->SetUsingActionSlot( true );

	// Ghosts cant use action items!
	if ( pLocalPlayer->m_Shared.InCond( TF_COND_HALLOWEEN_GHOST_MODE ) )
	{
		return;
	}

	// If we're in Mann Vs MAchine, and we're dead, we can use this to respawn instantly.
	if ( TFGameRules() && TFGameRules()->IsMannVsMachineMode() && pLocalPlayer->IsObserver() )
	{
		float flNextRespawn = TFGameRules()->GetNextRespawnWave( pLocalPlayer->GetTeamNumber(), pLocalPlayer );
		if ( flNextRespawn )
		{
			int iRespawnWait = (flNextRespawn - gpGlobals->curtime);
			if ( iRespawnWait > 1.0 )
			{
				engine->ClientCmd_Unrestricted( "td_buyback\n" );
				return;
			}
		}
	}

	// trying to pick up a dropped weapon?
	if ( pLocalPlayer->GetDroppedWeaponInRange() != NULL )
	{
		KeyValues *kv = new KeyValues( "+use_action_slot_item_server" );
		engine->ServerCmdKeyValues( kv );
		return;
	}

	if ( TFGameRules() && TFGameRules()->IsUsingGrapplingHook() )
	{
		CTFGrapplingHook *pGrapplingHook = dynamic_cast< CTFGrapplingHook* >( pLocalPlayer->GetEntityForLoadoutSlot( LOADOUT_POSITION_ACTION ) );
		if ( pGrapplingHook )
		{
			if ( pLocalPlayer->GetActiveTFWeapon() != pGrapplingHook )
			{
				pLocalPlayer->Weapon_Switch( pGrapplingHook );
			}

			KeyValues *kv = new KeyValues( "+use_action_slot_item_server" );
			engine->ServerCmdKeyValues( kv );

			return;
		}
	}

	// send a request to the GC to use the item
	g_bUsedGCItem = false;
	CEconItemView *pItem = CTFPlayerSharedUtils::GetEconItemViewByLoadoutSlot( pLocalPlayer, LOADOUT_POSITION_ACTION );
	if( pItem )
	{
		const IEconTool *pEconTool = pItem->GetItemDefinition()->GetEconTool();
		bool bIsRecharger = ( pEconTool && FStrEq( pEconTool->GetTypeName(), "item_eater_recharger" ) );
		if ( IsGCUseableItem( pItem->GetItemDefinition() ) && pItem->GetItemQuantity() >= 1 && !bIsRecharger )
		{
			UseConsumableItem( pItem, NULL );
			g_bUsedGCItem = true;
		}
	}
	
	// otherwise, forward to game server
	if ( !g_bUsedGCItem )
	{
		KeyValues *kv = new KeyValues( "+use_action_slot_item_server" );
		engine->ServerCmdKeyValues( kv );
	}
}

static ConCommand start_use_action_slot_item( "+use_action_slot_item", StartUseActionSlotItem, "Use the item in the action slot." );

static void EndUseActionSlotItem( const CCommand &args )
{
	C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
	if ( !pLocalPlayer )
		return;

	pLocalPlayer->SetUsingActionSlot( false );

	if ( TFGameRules() && TFGameRules()->IsUsingGrapplingHook() && pLocalPlayer->GetActiveTFWeapon() )
	{
		// if we're using the hook, switch back to the last weapon
		if ( pLocalPlayer->GetActiveTFWeapon()->GetWeaponID() == TF_WEAPON_GRAPPLINGHOOK )
		{
			KeyValues *kv = new KeyValues( "-use_action_slot_item_server" );
			engine->ServerCmdKeyValues( kv );

			C_BaseCombatWeapon* pLastWeapon = pLocalPlayer->GetLastWeapon();

			// switch away from the hook
			if ( pLastWeapon && pLocalPlayer->Weapon_CanSwitchTo( pLastWeapon ) )
			{
				pLocalPlayer->Weapon_Switch( pLastWeapon );
			}
			else
			{
				// in case we failed to switch back to last weapon for some reason, just find the next best
				pLocalPlayer->SwitchToNextBestWeapon( pLastWeapon );
			}

			return;
		}
	}

	// tell the game server we let go of the button if this wasn't a GC item
	if ( !g_bUsedGCItem )
	{
		KeyValues *kv = new KeyValues( "-use_action_slot_item_server" );
		engine->ServerCmdKeyValues( kv );
	}
}

static ConCommand end_use_action_slot_item( "-use_action_slot_item", EndUseActionSlotItem );


static void StartContextAction( const CCommand &args )
{
	// Assume we're going to taunt
	bool bDoTaunt = true;

	if ( TFGameRules() && TFGameRules()->IsMannVsMachineMode() )
	{
		C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
		if ( pLocalPlayer )
		{
			CTFPowerupBottle *pPowerupBottle = dynamic_cast< CTFPowerupBottle* >( pLocalPlayer->GetEquippedWearableForLoadoutSlot( LOADOUT_POSITION_ACTION ) );
			if ( pPowerupBottle && pPowerupBottle->GetNumCharges() > 0 )
			{
				// They're in MvM and have a bottle with a charge, so do an action instead
				bDoTaunt = false;
			}

			if ( pLocalPlayer->IsPlayerClass( TF_CLASS_HEAVYWEAPONS ) && pLocalPlayer->GetActiveTFWeapon() && pLocalPlayer->GetActiveTFWeapon()->GetWeaponID() == TF_WEAPON_MINIGUN )
			{
				int iRage = 0;
				CALL_ATTRIB_HOOK_INT_ON_OTHER( pLocalPlayer, iRage, generate_rage_on_dmg );
				if ( iRage )
				{
					if ( pLocalPlayer->m_Shared.GetRageMeter() >= 100.f && !pLocalPlayer->m_Shared.IsRageDraining() )
					{
						// They have rage ready to go, do the taunt
						bDoTaunt = true;
					}
				}
			}
		}
	}

	if ( bDoTaunt )
	{
		// Taunt
		engine->ClientCmd_Unrestricted( "+taunt\n" );
	}
	else
	{
		// Action item
		StartUseActionSlotItem( args );
	}
}

static ConCommand start_context_action( "+context_action", StartContextAction, "Use the item in the action slot." );

static void EndContextAction( const CCommand &args )
{
	// Undo both to be on the safe side
	EndUseActionSlotItem( args );
	engine->ClientCmd_Unrestricted( "-taunt\n" );
}

static ConCommand end_context_action( "-context_action", EndContextAction );

//-----------------------------------------------------------------------------

class CTFGiftNotification : public CEconNotification
{
public:
	CTFGiftNotification( GCSDK::CProtoBufMsg<CMsgGCGiftedItems> &msg ) 
		: CEconNotification() 
	{
		const EUniverse eUniverse = GetUniverse();

		Assert( msg.Body().recipient_account_ids_size() > 0 );

		SetLifetime( 30.0f );

		m_bRandomPerson = msg.Body().has_was_random_person()
					   && msg.Body().was_random_person();

		const CSteamID gifterSteamID( msg.Body().gifter_steam_id(), eUniverse, k_EAccountTypeIndividual );
		SetSteamID( gifterSteamID );

		if ( m_bRandomPerson )
		{
			const CSteamID recipientSteamID( msg.Body().recipient_account_ids(0), eUniverse, k_EAccountTypeIndividual );
			if ( msg.Body().recipient_account_ids_size() > 0 )
			{
				// This might not really be a random gift but might instead be a gift they opened
				// themselves (ie., a shipment box).
				if ( recipientSteamID == gifterSteamID )
				{
					SetText( "#TF_GifterText_SelfOpen" );
				}
				else
				{
					SetText( "#TF_GifterText_Random" );

					char szRecipientName[ MAX_PLAYER_NAME_LENGTH ];
					GetPlayerNameBySteamID( recipientSteamID, szRecipientName, sizeof( szRecipientName ) );
					g_pVGuiLocalize->ConvertANSIToUnicode( szRecipientName, m_wszPlayerName, sizeof( m_wszPlayerName ) );
					AddStringToken( "recipient", m_wszPlayerName );
					m_vecSteamIDRecipients.AddToTail( recipientSteamID );
				}
			}
		}
		else
		{
			SetText( "#TF_GifterText_All" );

			for ( int i = 0; i < msg.Body().recipient_account_ids_size(); ++i )
			{
				const CSteamID recipientSteamID( msg.Body().recipient_account_ids(i), eUniverse, k_EAccountTypeIndividual );
				m_vecSteamIDRecipients.AddToTail( recipientSteamID );
			}
		}
		
		char szGifterName[ MAX_PLAYER_NAME_LENGTH ];
		GetPlayerNameBySteamID( m_steamID, szGifterName, sizeof( szGifterName ) );
		g_pVGuiLocalize->ConvertANSIToUnicode( szGifterName, m_wszPlayerName, sizeof( m_wszPlayerName ) );
		AddStringToken( "giver", m_wszPlayerName );

		PrintToChatLog();
		
		SetSoundFilename( "misc/happy_birthday.wav" );
	}

	void PrintToChatLog()
	{
		CBaseHudChat *pHUDChat = (CBaseHudChat *)GET_HUDELEMENT( CHudChat );
		if ( pHUDChat )
		{
			wchar_t *pFormat = g_pVGuiLocalize->Find( "TF_GiftedItems" );
			if ( pFormat == NULL )
			{
				return;
			}
			FOR_EACH_VEC( m_vecSteamIDRecipients, i )
			{
				const CSteamID &steamIDRecipient = m_vecSteamIDRecipients[i];
				char szRecipientName[ MAX_PLAYER_NAME_LENGTH ];
				szRecipientName[0] = '\0';
				GetPlayerNameBySteamID( steamIDRecipient, szRecipientName, sizeof( szRecipientName ) );
				if ( szRecipientName[0] == '\0' )
				{
					continue;
				}

				wchar_t wszRecipientName[MAX_PLAYER_NAME_LENGTH];
				g_pVGuiLocalize->ConvertANSIToUnicode( szRecipientName, wszRecipientName, sizeof( wszRecipientName ) );

				wchar_t wszNotification[1024]=L"";
				g_pVGuiLocalize->ConstructString_safe( wszNotification, 
												  pFormat,
												  2, m_wszPlayerName, wszRecipientName );

				char szAnsi[1024];
				g_pVGuiLocalize->ConvertUnicodeToANSI( wszNotification, szAnsi, sizeof(szAnsi) );
			
				pHUDChat->Printf( CHAT_FILTER_NONE, "%s", szAnsi );
			}
		}
	}

	virtual EType NotificationType() { return eType_Basic; }

	wchar_t m_wszPlayerName[ MAX_PLAYER_NAME_LENGTH ];
	bool m_bRandomPerson;
	CUtlVector< CSteamID > m_vecSteamIDRecipients;
};

//#ifdef _DEBUG
//CON_COMMAND( cl_gifts_test, "tests the gift ui." )
//{
//	if ( !engine->IsInGame() )
//	{
//		return;
//	}
//
//	C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
//	if ( pLocalPlayer == NULL )
//	{
//		return;
//	}
//
//	if ( steamapicontext == NULL || steamapicontext->SteamUser() == NULL )
//	{
//		return;
//	}
//
//	CSteamID steamID = steamapicontext->SteamUser()->GetSteamID();
//	GCSDK::CProtoBufMsg< CMsgGCGiftedItems > msg( k_EMsgGCGiftedItems );
//	msg.Body().m_ulGifterSteamID = steamID.ConvertToUint64();
//	msg.Body().m_bRandomPerson = ( args.ArgC() >= 2 );
//	msg.Body().m_unNumGiftRecipients = msg.Body().m_bRandomPerson ? 1 : 31;
//	for ( int i = 0; i < msg.Body().m_unNumGiftRecipients; ++i )
//	{
//		msg.AddUint64Data( steamID.ConvertToUint64() );
//	}
//	msg.ResetReadPtr();
//	NotificationQueue_Add( new CTFGiftNotification( msg ) );
//}
//#endif

//-----------------------------------------------------------------------------
// Purpose: Feedback to the local player who used an item
//-----------------------------------------------------------------------------
class CTFUseItemNotification : public CEconNotification
{
public:
	CTFUseItemNotification( EGCMsgUseItemResponse eResponse) 
		: CEconNotification() 
	{
		switch ( eResponse )
		{
		case k_EGCMsgUseItemResponse_ItemUsed: 		
			SetText( "#TF_UseItem_Success" );
			break;
		case k_EGCMsgUseItemResponse_GiftNoOtherPlayers:
			SetText( "#TF_UseItem_GiftNoPlayers" );
			break;
		case k_EGCMsgUseItemResponse_ServerError:
			SetText( "#TF_UseItem_Error" );
			break;
		case k_EGCMsgUseItemResponse_MiniGameAlreadyStarted:
			SetText( "#TF_UseItem_MiniGameAlreadyStarted" );
			break;
		case k_EGCMsgUseItemResponse_CannotBeUsedByAccount:
			SetText( "#TF_UseItem_CannotBeUsedByAccount" );
			break;
		default:
			Assert( !"Unknown response in CTFUseItemNotification!" );
		}
		SetLifetime( 20.0f );
	}

	virtual EType NotificationType() { return eType_Basic; }
};

//-----------------------------------------------------------------------------
// Purpose: Local player used an item and the GC responded with the status of that request
//-----------------------------------------------------------------------------
class CGCUseItemResponse : public GCSDK::CGCClientJob
{
public:
	CGCUseItemResponse( GCSDK::CGCClient *pClient ) : GCSDK::CGCClientJob( pClient ) {}
	virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
	{
		GCSDK::CGCMsg<MsgGCUseItemResponse_t> msg( pNetPacket );
		EGCMsgUseItemResponse eResponse = (EGCMsgUseItemResponse)msg.Body().m_eResponse;
		if ( eResponse == k_EGCMsgUseItemResponse_ItemUsed_ItemsGranted )
		{
			if ( s_bConsumableToolOpeningGift )
			{
				vgui::surface()->PlaySound( "ui/item_gift_wrap_unwrap.wav" );
			}
			else
			{
				vgui::surface()->PlaySound( "ui/item_open_crate.wav" );
			}

			ShowWaitingDialog( new CWaitForPackageDialog( NULL ), "#ToolDecodeInProgress", true, false, 5.0f );
		}
		else if ( eResponse != k_EGCMsgUseItemResponse_ItemUsed )
		{
			NotificationQueue_Add( new CTFUseItemNotification( (EGCMsgUseItemResponse)msg.Body().m_eResponse ) );
		}
		else
		{
			// refresh the backpack
			if ( EconUI()->GetBackpackPanel() )
			{
				EconUI()->GetBackpackPanel()->UpdateModelPanels();
			}
		}
		return true;
	}
};
GC_REG_JOB( GCSDK::CGCClient, CGCUseItemResponse, "CGCUseItemResponse", k_EMsgGCUseItemResponse, GCSDK::k_EServerTypeGCClient );

//-----------------------------------------------------------------------------
// Purpose: A player has gifted items
//-----------------------------------------------------------------------------
class CGCGiftedItems : public GCSDK::CGCClientJob
{
public:
	CGCGiftedItems( GCSDK::CGCClient *pClient ) : GCSDK::CGCClientJob( pClient ) {}
	virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
	{
		GCSDK::CProtoBufMsg<CMsgGCGiftedItems> msg( pNetPacket );

		if ( steamapicontext == NULL || steamapicontext->SteamFriends() == NULL )
		{
			return true;
		}

		char szGifterName[ MAX_PLAYER_NAME_LENGTH ];
		szGifterName[0] = '\0';
		GetPlayerNameBySteamID( CSteamID( msg.Body().gifter_steam_id(), GetUniverse(), k_EAccountTypeIndividual ), szGifterName, sizeof( szGifterName ) );
		if ( szGifterName[0] == '\0' )
		{
			return true;
		}
		
		// notify UI
		NotificationQueue_Add( new CTFGiftNotification( msg ) );
		return true;
	}
};
GC_REG_JOB( GCSDK::CGCClient, CGCGiftedItems, "CGCGiftedItems", k_EMsgGCGiftedItems, GCSDK::k_EServerTypeGCClient );

//-----------------------------------------------------------------------------
// Purpose: A player has used a claim code item
//-----------------------------------------------------------------------------
class CGCUsedClaimCodeItem : public GCSDK::CGCClientJob
{
public:
	CGCUsedClaimCodeItem( GCSDK::CGCClient *pClient ) : GCSDK::CGCClientJob( pClient ) {}
	virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
	{
		GCSDK::CGCMsg<MsgGCUsedClaimCodeItem_t> msg( pNetPacket );

		if ( steamapicontext == NULL )
		{
			return true;
		}

		CUtlString url;
		if ( msg.BReadStr( &url ) )
		{
			steamapicontext->SteamFriends()->ActivateGameOverlayToWebPage( url.Get() );
			IViewPortPanel *pMMOverride = ( gViewPortInterface->FindPanelByName( PANEL_MAINMENUOVERRIDE ) );
			if ( pMMOverride )
			{
				((CHudMainMenuOverride*)pMMOverride)->UpdatePromotionalCodes();
			}
		}

		return true;
	}
};
GC_REG_JOB( GCSDK::CGCClient, CGCUsedClaimCodeItem, "CGCUsedClaimCodeItem", k_EMsgGCUsedClaimCodeItem, GCSDK::k_EServerTypeGCClient );


//-----------------------------------------------------------------------------
// Duel mini-game 
//-----------------------------------------------------------------------------

class CDuelMiniGameEventListener;

struct duel_minigame_local_data_t
{
	duel_minigame_local_data_t()
		: m_pEventListener( NULL )
		, m_steamIDOpponent()
		, m_unMyScore( 0 )
		, m_unOpponentScore( 0 )
		, m_iRequiredPlayerClass( TF_CLASS_UNDEFINED )
	{
	}
	uint32 m_unMyScore;
	uint32 m_unOpponentScore;
	int m_iRequiredPlayerClass;
	CDuelMiniGameEventListener *m_pEventListener;
	CSteamID m_steamIDOpponent;
};
static duel_minigame_local_data_t gDuelMiniGameLocalData;

bool DuelMiniGame_IsDueling()
{
	return gDuelMiniGameLocalData.m_steamIDOpponent != CSteamID();
}

int DuelMiniGame_GetRequiredPlayerClass()
{
	return gDuelMiniGameLocalData.m_steamIDOpponent != CSteamID() ? gDuelMiniGameLocalData.m_iRequiredPlayerClass : TF_CLASS_UNDEFINED;
}

static void DuelMiniGame_Reset();
static bool RemoveRelatedDuelNotifications( CEconNotification* pNotification );

/**
 * Duel info notification
 */
class CTFDuelInfoNotification : public CEconNotification
{
public:
	CTFDuelInfoNotification()
	{
	}

	static bool IsDuelInfoNotification( CEconNotification *pNotification )
	{
		return dynamic_cast< CTFDuelInfoNotification* >( pNotification ) != NULL;
	}
};

/**
 * Duel Notification
 */
class CTFDuelRequestNotification : public CEconNotification, public CGameEventListener
{
public:
	CTFDuelRequestNotification( const char *pInitiatorName, const CSteamID &steamIDInitiator, const CSteamID &steamIDTarget, const int iRequiredPlayerClass ) 
		: CEconNotification() 
		, m_steamIDInitiator( steamIDInitiator )
		, m_steamIDTarget( steamIDTarget )
		, m_iRequiredPlayerClass( iRequiredPlayerClass )
	{
		g_pVGuiLocalize->ConvertANSIToUnicode( pInitiatorName, m_wszPlayerName, sizeof(m_wszPlayerName) );

		ListenForGameEvent( "teamplay_round_win" );
		ListenForGameEvent( "teamplay_round_stalemate" );
	}

	virtual EType NotificationType()
	{
		CSteamID localSteamID;
		C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
		if ( pLocalPlayer && pLocalPlayer->GetSteamID( &localSteamID ) && localSteamID == m_steamIDTarget )
		{
			return eType_AcceptDecline;
		}
		return eType_Basic;
	}

	// XXX(JohnS): Is there something that manually calls trigger here or is this dead code?
	virtual void Trigger()
	{
		CTFGenericConfirmDialog *pDialog = ShowConfirmDialog( "#TF_Duel_Title",  "#TF_Duel_Request", "#GameUI_OK", "#TF_Duel_JoinCancel", &ConfirmDuel );
		pDialog->SetContext( this );
		pDialog->AddStringToken( "initiator", m_wszPlayerName );
		// so we aren't deleted
		SetIsInUse( true );
	}

	virtual void Accept()
	{
		ConfirmDuel( true, this );
	}

	virtual void Decline()
	{
		ConfirmDuel( false, this );
	}

	static bool IsDuelRequestNotification( CEconNotification *pNotification )
	{
		return dynamic_cast< CTFDuelRequestNotification* >( pNotification ) != NULL;
	}

	static void ConfirmDuel( bool bConfirmed, void *pContext )
	{
		CTFDuelRequestNotification *pNotification = (CTFDuelRequestNotification*)pContext;

		// if this is a class restricted duel, then make sure the local player is the same class before
		// they can accept
		C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
		if ( bConfirmed && pLocalPlayer && pNotification->m_iRequiredPlayerClass != TF_CLASS_UNDEFINED )
		{
			int iClass = pLocalPlayer->m_Shared.GetDesiredPlayerClassIndex();
			if ( pNotification->m_iRequiredPlayerClass != iClass )
			{
				KeyValues *pKeyValues = new KeyValues( "DuelConfirm" );
				switch ( pNotification->m_iRequiredPlayerClass )
				{
				case TF_CLASS_SCOUT: 			pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Scout" ) ); break;
				case TF_CLASS_SNIPER: 			pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Sniper" ) ); break;
				case TF_CLASS_SOLDIER: 			pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Soldier" ) ); break;
				case TF_CLASS_DEMOMAN: 			pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Demoman" ) ); break;
				case TF_CLASS_MEDIC: 			pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Medic" ) ); break;
				case TF_CLASS_HEAVYWEAPONS: 	pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_HWGuy" ) ); break;
				case TF_CLASS_PYRO: 			pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Pyro" ) ); break;
				case TF_CLASS_SPY: 				pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Spy" ) ); break;
				case TF_CLASS_ENGINEER: 		pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Engineer" ) ); break;
				}
				ShowMessageBox( "#TF_Duel_Title",  "#TF_Duel_WrongClass", pKeyValues, "#GameUI_OK" );
				return;
			}
		}

		// notify GC of our choice
		GCSDK::CGCMsg< MsgGC_Duel_Response_t > msg( k_EMsgGC_Duel_Response );
		msg.Body().m_ulInitiatorSteamID = pNotification->m_steamIDInitiator.ConvertToUint64();
		msg.Body().m_ulTargetSteamID = pNotification->m_steamIDTarget.ConvertToUint64();
		msg.Body().m_bAccepted = bConfirmed;
		GCClientSystem()->BSendMessage( msg );
		pNotification->SetIsInUse( false );
		pNotification->MarkForDeletion();

		// remove all duel notifications if we've accepted
		if ( bConfirmed )
		{
			NotificationQueue_Remove( &RemoveRelatedDuelNotifications );
		}
	}

	void FireGameEvent( IGameEvent *event )
	{
		const char *pEventName = event->GetName();
		if ( FStrEq( "teamplay_round_win", pEventName ) || FStrEq( "teamplay_round_stalemate", pEventName ) )
		{
			Decline();
			return;
		}
	}

	CSteamID m_steamIDInitiator;
	CSteamID m_steamIDTarget;
	int m_iRequiredPlayerClass;
	wchar_t m_wszPlayerName[MAX_PLAYER_NAME_LENGTH];
};

/**
 * Listens for duel_status events and adds a notification.  Ideally adds to a scoreboard or something...
 */
class CDuelMiniGameEventListener : public CGameEventListener
{
public:
	CDuelMiniGameEventListener()
	{
		ListenForGameEvent( "duel_status" );
		ListenForGameEvent( "teamplay_round_win" );
		ListenForGameEvent( "teamplay_round_stalemate" );
	}

	virtual void FireGameEvent( IGameEvent *event )
	{
		const char *pEventName = event->GetName();

		C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
		if ( pLocalPlayer == NULL )
		{
			return;
		}

		if ( Q_strcmp( "teamplay_round_win", pEventName ) == 0 || Q_strcmp( "teamplay_round_stalemate", pEventName ) == 0 )
		{
			DuelMiniGame_Reset();
			return;
		}
		else if ( Q_strcmp( "duel_status", pEventName ) == 0 )
		{
			int iKillerID = engine->GetPlayerForUserID( event->GetInt( "killer" ) );
			int iInitiatorID = engine->GetPlayerForUserID( event->GetInt( "initiator" ) );
			int iTargetID = engine->GetPlayerForUserID( event->GetInt( "target" ) );

			const char *pInitiatorName = ( iInitiatorID > 0 ? g_PR->GetPlayerName( iInitiatorID ) : "" );
			wchar_t wszInitiatorName[MAX_PLAYER_NAME_LENGTH] = L"";
			g_pVGuiLocalize->ConvertANSIToUnicode( pInitiatorName, wszInitiatorName, sizeof(wszInitiatorName) );

			const char *pTargetName = ( iTargetID > 0 ? g_PR->GetPlayerName( iTargetID ) : "" );
			wchar_t wszTargetName[MAX_PLAYER_NAME_LENGTH] = L"";
			g_pVGuiLocalize->ConvertANSIToUnicode( pTargetName, wszTargetName, sizeof(wszTargetName) );

			wchar_t wszInitiatorScore[16];
			_snwprintf( wszInitiatorScore, ARRAYSIZE( wszInitiatorScore ), L"%i", event->GetInt( "initiator_score", 0 ) );
			wchar_t wszTargetScore[16];
			_snwprintf( wszTargetScore, ARRAYSIZE( wszTargetScore ), L"%i", event->GetInt( "target_score", 0 ) );

			enum
			{
				kDuelScoreType_Kill,
				kDuelScoreType_Assist,
				kMaxDuelScoreTypes,
			};
			
			int iScoreType = event->GetInt( "score_type" );

			KeyValues *pKeyValues = new KeyValues( "DuelStatus" );
			pKeyValues->SetWString( "killer", iKillerID == iInitiatorID ? wszInitiatorName : wszTargetName );
			pKeyValues->SetWString( "initiator", wszInitiatorName );
			pKeyValues->SetWString( "target", wszTargetName );
			pKeyValues->SetWString( "initiator_score", wszInitiatorScore );
			pKeyValues->SetWString( "target_score", wszTargetScore );
			
			// if we aren't involved in the duel, don't show the notification
			if ( pLocalPlayer->entindex() == iInitiatorID || pLocalPlayer->entindex() == iTargetID )
			{
				// remove existing duel info notifications
				NotificationQueue_Remove( &RemoveRelatedDuelNotifications );
				// add new one
				CTFDuelInfoNotification *pNotification = new CTFDuelInfoNotification();
				pNotification->SetLifetime( 10.0f );
				pNotification->SetText( iScoreType == kDuelScoreType_Kill ? "TF_Duel_StatusKill" : "TF_Duel_StatusAssist" );
				pNotification->SetKeyValues( pKeyValues );
				pNotification->SetSoundFilename( "ui/duel_event.wav" );
				player_info_t pi;
				if ( engine->GetPlayerInfo( iKillerID, &pi ) && pi.friendsID != 0 )
				{
					CSteamID steamID( pi.friendsID, 1, GetUniverse(), k_EAccountTypeIndividual );
					pNotification->SetSteamID( steamID );
				}
				NotificationQueue_Add( pNotification );
				if ( pLocalPlayer->entindex() == iInitiatorID )
				{
					gDuelMiniGameLocalData.m_unMyScore = event->GetInt( "initiator_score" );
					gDuelMiniGameLocalData.m_unOpponentScore = event->GetInt( "target_score" );
				}
				else
				{
					gDuelMiniGameLocalData.m_unMyScore = event->GetInt( "target_score" );
					gDuelMiniGameLocalData.m_unOpponentScore = event->GetInt( "initiator_score" );
				}
			}

			// print to chat log
			PrintTextToChat( iScoreType == kDuelScoreType_Kill ? "TF_Duel_StatusForChat_Kill" : "TF_Duel_StatusForChat_Assist", pKeyValues );

			// cleanup
			pKeyValues->deleteThis();
		}
	}
};

/**
 * Duel request
 */
class CGC_Duel_Request : public GCSDK::CGCClientJob
{
public:
	CGC_Duel_Request( GCSDK::CGCClient *pClient ) : GCSDK::CGCClientJob( pClient ) {}
	virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
	{
		GCSDK::CGCMsg<MsgGC_Duel_Request_t> msg( pNetPacket );
		CSteamID localSteamID;
		C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
		if ( pLocalPlayer == NULL || pLocalPlayer->GetSteamID( &localSteamID ) == false )
		{
			return true;
		}

		// get player names
		CSteamID steamIDInitiator( msg.Body().m_ulInitiatorSteamID );
		CSteamID steamIDTarget( msg.Body().m_ulTargetSteamID );

		// ignore blocked players (we don't want to print out to the console either)
		if ( IgnoreRequestFromUser( steamIDInitiator ) || IgnoreRequestFromUser( steamIDTarget ) )
		{
			GCSDK::CGCMsg< MsgGC_Duel_Response_t > msgGC( k_EMsgGC_Duel_Response );
			msgGC.Body().m_ulInitiatorSteamID = steamIDInitiator.ConvertToUint64();
			msgGC.Body().m_ulTargetSteamID = steamIDTarget.ConvertToUint64();
			msgGC.Body().m_bAccepted = false;
			GCClientSystem()->BSendMessage( msgGC );
			return true;
		}

		char szPlayerName_Initiator[ MAX_PLAYER_NAME_LENGTH ];
		GetPlayerNameBySteamID( steamIDInitiator, szPlayerName_Initiator, sizeof( szPlayerName_Initiator ) );
		char szPlayerName_Target[ MAX_PLAYER_NAME_LENGTH ];
		GetPlayerNameBySteamID( steamIDTarget, szPlayerName_Target, sizeof( szPlayerName_Target ) );
		wchar_t wszPlayerName_Initiator[MAX_PLAYER_NAME_LENGTH];
		wchar_t wszPlayerName_Target[MAX_PLAYER_NAME_LENGTH];
		g_pVGuiLocalize->ConvertANSIToUnicode( szPlayerName_Initiator, wszPlayerName_Initiator, sizeof(wszPlayerName_Initiator) );
		g_pVGuiLocalize->ConvertANSIToUnicode( szPlayerName_Target, wszPlayerName_Target, sizeof(wszPlayerName_Target) );

		// add notification
		KeyValues *pKeyValues = new KeyValues( "DuelText" );
		pKeyValues->SetWString( "initiator", wszPlayerName_Initiator );
		pKeyValues->SetWString( "target", wszPlayerName_Target );

		const char *pText = localSteamID == steamIDTarget ? "TF_Duel_Request" : "TF_Duel_Challenge";
		const char *pSoundFilename = "ui/duel_challenge.wav";
		if ( msg.Body().m_usAsPlayerClass >= TF_FIRST_NORMAL_CLASS && msg.Body().m_usAsPlayerClass < TF_LAST_NORMAL_CLASS )
		{
			pText = localSteamID == steamIDTarget ? "TF_Duel_Request_Class" : "TF_Duel_Challenge_Class";
			pSoundFilename = "ui/duel_challenge_with_restriction.wav";
			switch ( msg.Body().m_usAsPlayerClass )
			{
			case TF_CLASS_SCOUT: 			pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Scout" ) ); break;
			case TF_CLASS_SNIPER: 			pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Sniper" ) ); break;
			case TF_CLASS_SOLDIER: 			pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Soldier" ) ); break;
			case TF_CLASS_DEMOMAN: 			pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Demoman" ) ); break;
			case TF_CLASS_MEDIC: 			pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Medic" ) ); break;
			case TF_CLASS_HEAVYWEAPONS: 	pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_HWGuy" ) ); break;
			case TF_CLASS_PYRO: 			pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Pyro" ) ); break;
			case TF_CLASS_SPY: 				pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Spy" ) ); break;
			case TF_CLASS_ENGINEER: 		pKeyValues->SetWString( "player_class", g_pVGuiLocalize->Find( "#TF_Class_Name_Engineer" ) ); break;
			}
		}
		if ( localSteamID == steamIDInitiator || localSteamID == steamIDTarget )
		{
			CTFDuelRequestNotification *pNotification = new CTFDuelRequestNotification( szPlayerName_Initiator, steamIDInitiator, steamIDTarget, msg.Body().m_usAsPlayerClass );
			pNotification->SetLifetime( localSteamID == steamIDTarget ? 30.0f : 7.0f );
			pNotification->SetText( pText );
			pNotification->SetKeyValues( pKeyValues );
			pNotification->SetSteamID( steamIDInitiator );
			pNotification->SetSoundFilename( pSoundFilename );
			NotificationQueue_Add( pNotification );
		}

		// print to chat log
		PrintTextToChat( pText, pKeyValues );

		pKeyValues->deleteThis();

		return true;
	}
protected:
};
GC_REG_JOB( GCSDK::CGCClient, CGC_Duel_Request, "CGC_Duel_Request", k_EMsgGC_Duel_Request, GCSDK::k_EServerTypeGCClient );

/**
 * Duel response
 */
class CGCClient_Duel_Response : public GCSDK::CGCClientJob
{
public:
	CGCClient_Duel_Response( GCSDK::CGCClient *pClient ) : GCSDK::CGCClientJob( pClient ) {}
	virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
	{
		GCSDK::CGCMsg<MsgGC_Duel_Response_t> msg( pNetPacket );
		CSteamID localSteamID;
		C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
		if ( pLocalPlayer == NULL || pLocalPlayer->GetSteamID( &localSteamID ) == false )
			return true;

		// get player names
		CSteamID steamIDInitiator( msg.Body().m_ulInitiatorSteamID );
		CSteamID steamIDTarget( msg.Body().m_ulTargetSteamID );
		char szPlayerName_Initiator[ MAX_PLAYER_NAME_LENGTH ];
		GetPlayerNameBySteamID( steamIDInitiator, szPlayerName_Initiator, sizeof( szPlayerName_Initiator ) );
		char szPlayerName_Target[ MAX_PLAYER_NAME_LENGTH ];
		GetPlayerNameBySteamID( steamIDTarget, szPlayerName_Target, sizeof( szPlayerName_Target ) );
		wchar_t wszPlayerName_Initiator[MAX_PLAYER_NAME_LENGTH];
		wchar_t wszPlayerName_Target[MAX_PLAYER_NAME_LENGTH];
		g_pVGuiLocalize->ConvertANSIToUnicode( szPlayerName_Initiator, wszPlayerName_Initiator, sizeof(wszPlayerName_Initiator) );
		g_pVGuiLocalize->ConvertANSIToUnicode( szPlayerName_Target, wszPlayerName_Target, sizeof(wszPlayerName_Target) );

		KeyValues *pKeyValues = new KeyValues( "DuelText" );
		pKeyValues->SetWString( "initiator", wszPlayerName_Initiator );
		pKeyValues->SetWString( "target", wszPlayerName_Target );

		bool bIsClassDuel = msg.Body().m_usAsPlayerClass >= TF_FIRST_NORMAL_CLASS && msg.Body().m_usAsPlayerClass < TF_LAST_NORMAL_CLASS;

		// add notification
		const char *pText = "TF_Duel_Accept";
		const char *pSoundFilename = bIsClassDuel ? "ui/duel_challenge_accepted_with_restriction.wav" : "ui/duel_challenge_accepted.wav";
		if ( msg.Body().m_bAccepted == false )
		{
			const char *kDeclineStrings[] = {
				"TF_Duel_Decline",
				"TF_Duel_Decline2",
				"TF_Duel_Decline3"
			};
			pText = kDeclineStrings[ RandomInt( 0, ARRAYSIZE( kDeclineStrings ) - 1 ) ];
			pSoundFilename = bIsClassDuel ? "ui/duel_challenge_rejected_with_restriction.wav" : "ui/duel_challenge_rejected.wav";
		}

		if ( ( TFGameRules() && TFGameRules()->CanInitiateDuels() ) || msg.Body().m_bAccepted )
		{
			if ( localSteamID == steamIDInitiator || localSteamID == steamIDTarget )
			{
				// remove existing duel info notifications
				NotificationQueue_Remove( &RemoveRelatedDuelNotifications );
				// add new one
				CTFDuelInfoNotification *pNotification = new CTFDuelInfoNotification();
				pNotification->SetLifetime( 7.0f );
				pNotification->SetText( pText );
				pNotification->SetKeyValues( pKeyValues );
				pNotification->SetSteamID( steamIDInitiator );
				pNotification->SetSoundFilename( pSoundFilename );
				NotificationQueue_Add( pNotification );
			}

			// print to chat
			PrintTextToChat( pText, pKeyValues );
		}

		// store away opponent id and create event listener if applicable
		if ( msg.Body().m_bAccepted )
		{
			if ( localSteamID == steamIDInitiator )
			{
				gDuelMiniGameLocalData.m_steamIDOpponent = steamIDTarget;
			}
			else if ( localSteamID == steamIDTarget )
			{
				gDuelMiniGameLocalData.m_steamIDOpponent = steamIDInitiator;
			}
			if ( gDuelMiniGameLocalData.m_pEventListener == NULL )
			{
				gDuelMiniGameLocalData.m_pEventListener = new CDuelMiniGameEventListener();
			}
			gDuelMiniGameLocalData.m_iRequiredPlayerClass = msg.Body().m_usAsPlayerClass;
		}
		
		pKeyValues->deleteThis();

		return true;
	}
protected:
};
GC_REG_JOB( GCSDK::CGCClient, CGCClient_Duel_Response, "CGCClient_Duel_Response", k_EMsgGC_Duel_Response, GCSDK::k_EServerTypeGCClient );

/**
 * Duel status (whether the duel is in progress or cancelled)
 */
class CGC_Duel_Status : public GCSDK::CGCClientJob
{
public:
	CGC_Duel_Status( GCSDK::CGCClient *pClient ) : GCSDK::CGCClientJob( pClient ) {}
	virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
	{
		GCSDK::CGCMsg<MsgGC_Duel_Status_t> msg( pNetPacket );
		// get player names
		CSteamID steamIDInitiator( msg.Body().m_ulInitiatorSteamID );
		CSteamID steamIDTarget( msg.Body().m_ulTargetSteamID );
		char szPlayerName_Initiator[ MAX_PLAYER_NAME_LENGTH ];
		GetPlayerNameBySteamID( steamIDInitiator, szPlayerName_Initiator, sizeof( szPlayerName_Initiator ) );
		char szPlayerName_Target[ MAX_PLAYER_NAME_LENGTH ];
		GetPlayerNameBySteamID( steamIDTarget, szPlayerName_Target, sizeof( szPlayerName_Target ) );
		wchar_t wszPlayerName_Initiator[MAX_PLAYER_NAME_LENGTH];
		wchar_t wszPlayerName_Target[MAX_PLAYER_NAME_LENGTH];
		g_pVGuiLocalize->ConvertANSIToUnicode( szPlayerName_Initiator, wszPlayerName_Initiator, sizeof(wszPlayerName_Initiator) );
		g_pVGuiLocalize->ConvertANSIToUnicode( szPlayerName_Target, wszPlayerName_Target, sizeof(wszPlayerName_Target) );

		// add notification
		const char *pText = "TF_Duel_InProgress";
		switch ( msg.Body().m_usStatus )
		{
		case kDuel_Status_AlreadyInDuel_Inititator: 
			pText = "TF_Duel_InADuel_Initiator"; 
			break;
		case kDuel_Status_AlreadyInDuel_Target: 
			pText = "TF_Duel_InADuel_Target"; 
			break;
		case kDuel_Status_DuelBanned_Initiator:
			pText = "TF_Duel_TempBanned_Initiator"; 
			break;
		case kDuel_Status_DuelBanned_Target:
			pText = "TF_Duel_TempBanned_Target"; 
			break;
		case kDuel_Status_Cancelled:
			pText = "TF_Duel_Cancelled";
			break;
		case kDuel_Status_MissingSession:
			pText = "TF_Duel_UserTemporarilyUnavailable";
			break;
		default:
			AssertMsg1( false, "Unknown duel status %i in CGC_Duel_Status!", msg.Body().m_usStatus );
		}
		// remove existing duel info notifications
		NotificationQueue_Remove( &RemoveRelatedDuelNotifications );
		// add new one
		CTFDuelInfoNotification *pNotification = new CTFDuelInfoNotification();
		pNotification->SetLifetime( 7.0f );
		pNotification->SetText( pText );
		pNotification->AddStringToken( "initiator", wszPlayerName_Initiator );
		pNotification->AddStringToken( "target", wszPlayerName_Target );
		pNotification->SetSteamID( steamIDInitiator );
		pNotification->SetSoundFilename( "ui/duel_event.wav" );
		NotificationQueue_Add( pNotification );
		return true;
	}
protected:
};
GC_REG_JOB( GCSDK::CGCClient, CGC_Duel_Status, "CGC_Duel_Status", k_EMsgGC_Duel_Status, GCSDK::k_EServerTypeGCClient );

/**
 * Duel Results--ideally this is a scoreboard as well.
 */
class CGC_Duel_Results : public GCSDK::CGCClientJob
{
public:
	CGC_Duel_Results( GCSDK::CGCClient *pClient ) : GCSDK::CGCClientJob( pClient ) {}
	virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
	{
		GCSDK::CGCMsg<MsgGC_Duel_Results_t> msg( pNetPacket );

		if ( steamapicontext == NULL || steamapicontext->SteamUser() == NULL )
			return true;
		
		CSteamID localSteamID = steamapicontext->SteamUser()->GetSteamID();

		// get player names
		CSteamID steamIDWinner( msg.Body().m_ulWinnerSteamID );
		CSteamID steamIDInitiator( msg.Body().m_ulInitiatorSteamID );
		CSteamID steamIDTarget( msg.Body().m_ulTargetSteamID );
		char szPlayerName_Winner[ MAX_PLAYER_NAME_LENGTH ];
		GetPlayerNameBySteamID( steamIDWinner, szPlayerName_Winner, sizeof( szPlayerName_Winner ) );
		char szPlayerName_Initiator[ MAX_PLAYER_NAME_LENGTH ];
		GetPlayerNameBySteamID( steamIDInitiator, szPlayerName_Initiator, sizeof( szPlayerName_Initiator ) );
		char szPlayerName_Target[ MAX_PLAYER_NAME_LENGTH ];
		GetPlayerNameBySteamID( steamIDTarget, szPlayerName_Target, sizeof( szPlayerName_Target ) );
		wchar_t wszPlayerName_Winner[MAX_PLAYER_NAME_LENGTH];
		wchar_t wszPlayerName_Initiator[MAX_PLAYER_NAME_LENGTH];
		wchar_t wszPlayerName_Target[MAX_PLAYER_NAME_LENGTH];
		g_pVGuiLocalize->ConvertANSIToUnicode( szPlayerName_Winner, wszPlayerName_Winner, sizeof(wszPlayerName_Winner) );
		g_pVGuiLocalize->ConvertANSIToUnicode( szPlayerName_Initiator, wszPlayerName_Initiator, sizeof(wszPlayerName_Initiator) );
		g_pVGuiLocalize->ConvertANSIToUnicode( szPlayerName_Target, wszPlayerName_Target, sizeof(wszPlayerName_Target) );

		// build text
		bool bTie = msg.Body().m_usScoreInitiator == msg.Body().m_usScoreTarget;
		const char *pText = "TF_Duel_Win";
		switch ( msg.Body().m_usEndReason )
		{
		case kDuelEndReason_DuelOver:
			break;
		case kDuelEndReason_PlayerDisconnected:
			bTie = false;
			pText = "TF_Duel_Win_Disconnect";
			break;
		case kDuelEndReason_PlayerSwappedTeams:
			bTie = false;
			pText = "TF_Duel_Win_SwappedTeams";
			break;
		case kDuelEndReason_LevelShutdown:
			bTie = true;
			pText = "TF_Duel_Refund_LevelShutdown";
			break;
		case kDuelEndReason_ScoreTiedAtZero:
			bTie = true;
			pText = "TF_Duel_Refund_ScoreTiedAtZero";
			break;
		case kDuelEndReason_ScoreTied:
			bTie = true;
			pText = "TF_Duel_Tie";
			break;
		case kDuelEndReason_PlayerKicked:
			bTie = true;
			pText = "TF_Duel_Refund_Kicked";
			break;
		case kDuelEndReason_PlayerForceSwappedTeams:
			bTie = true;
			pText = "TF_Duel_Refund_ForceTeamSwap";
			break;
		case kDuelEndReason_Cancelled:
			bTie = true;
			pText = "TF_Duel_Cancelled";
			break;
		}

		KeyValues *pKeyValues = new KeyValues( "DuelResults" );
		if ( bTie == false )
		{
			pKeyValues->SetWString( "winner", wszPlayerName_Winner );
			pKeyValues->SetWString( "loser", steamIDWinner == steamIDInitiator ? wszPlayerName_Target : wszPlayerName_Initiator );
			wchar_t wszScoreInitiator[16];
			wchar_t wszScoreTarget[16];
			_snwprintf( wszScoreInitiator, ARRAYSIZE( wszScoreInitiator ), L"%u", (uint32)msg.Body().m_usScoreInitiator );
			_snwprintf( wszScoreTarget, ARRAYSIZE( wszScoreTarget ), L"%u", (uint32)msg.Body().m_usScoreTarget );
			pKeyValues->SetWString( "winner_score", steamIDWinner == steamIDInitiator ? wszScoreInitiator : wszScoreTarget );
			pKeyValues->SetWString( "loser_score", steamIDWinner == steamIDInitiator ? wszScoreTarget : wszScoreInitiator );
		}
		else
		{
			wchar_t wszScoreInitiator[16];
			_snwprintf( wszScoreInitiator, ARRAYSIZE( wszScoreInitiator ), L"%u", (uint32)msg.Body().m_usScoreInitiator );
			pKeyValues->SetWString( "score", wszScoreInitiator );
			pKeyValues->SetWString( "initiator", wszPlayerName_Initiator );
			pKeyValues->SetWString( "target", wszPlayerName_Target );
		}

		// add notification
		if ( localSteamID == steamIDInitiator || localSteamID == steamIDTarget )
		{
			// remove existing duel info notifications
			NotificationQueue_Remove( &RemoveRelatedDuelNotifications );
			// add new one
			CTFDuelInfoNotification *pNotification = new CTFDuelInfoNotification();
			pNotification->SetText( pText );
			pNotification->SetKeyValues( pKeyValues );
			pNotification->SetSteamID( bTie == false ? steamIDWinner : ( localSteamID == steamIDInitiator ? steamIDTarget : steamIDInitiator ) );
			pNotification->SetSoundFilename( "ui/duel_event.wav" );
			NotificationQueue_Add( pNotification );
			gDuelMiniGameLocalData.m_steamIDOpponent = CSteamID();
		}
		
		// print out to chat
		PrintTextToChat( pText, pKeyValues );

		// cleanup
		pKeyValues->deleteThis();

		// reset the dueling minigame
		DuelMiniGame_Reset();

		return true;
	}
protected:
};
GC_REG_JOB( GCSDK::CGCClient, CGC_Duel_Results, "CGC_Duel_Results", k_EMsgGC_Duel_Results, GCSDK::k_EServerTypeGCClient );

static bool RemoveRelatedDuelNotifications( CEconNotification *pNotification )
{
	return ( CTFDuelRequestNotification::IsDuelRequestNotification( pNotification ) || 
			 CTFDuelInfoNotification::IsDuelInfoNotification( pNotification ) );
}

static void DuelMiniGame_Reset()
{
	delete gDuelMiniGameLocalData.m_pEventListener;
	gDuelMiniGameLocalData.m_pEventListener = NULL;
	gDuelMiniGameLocalData.m_steamIDOpponent = CSteamID();
	gDuelMiniGameLocalData.m_unMyScore = 0;
	gDuelMiniGameLocalData.m_unOpponentScore = 0;
	gDuelMiniGameLocalData.m_iRequiredPlayerClass = TF_CLASS_UNDEFINED;
}

bool DuelMiniGame_IsDuelingLocalPlayer( C_TFPlayer *pPlayer )
{
	CSteamID steamID;
	if ( pPlayer->GetSteamID( &steamID ) )
	{
		return ( steamID == gDuelMiniGameLocalData.m_steamIDOpponent );
	}
	return false;
}

bool DuelMiniGame_GetStats( C_TFPlayer **ppPlayer, uint32 &unMyScore, uint32 &unOpponentScore )
{
	*ppPlayer = NULL;
	int iLocalPlayerIndex =  GetLocalPlayerIndex();
	for( int iPlayerIndex = 1 ; iPlayerIndex <= MAX_PLAYERS; iPlayerIndex++ )
	{
		// find all players who are on the local player's team
		if( ( iPlayerIndex != iLocalPlayerIndex ) && ( g_PR->IsConnected( iPlayerIndex ) ) )
		{
			CSteamID steamID;
			C_TFPlayer *pPlayer = ToTFPlayer( UTIL_PlayerByIndex( iPlayerIndex ) );
			if ( pPlayer && pPlayer->GetSteamID( &steamID ) && steamID == gDuelMiniGameLocalData.m_steamIDOpponent ) 
			{
				*ppPlayer = pPlayer;
				break;
			}
		}
	}
	static bool sbTesting = false;
	if ( sbTesting )
	{
		*ppPlayer = ToTFPlayer( C_BasePlayer::GetLocalPlayer() );
	}
	if ( *ppPlayer != NULL )
	{
		CSteamID steamID = steamapicontext->SteamUser()->GetSteamID();
		unMyScore = gDuelMiniGameLocalData.m_unMyScore;
		unOpponentScore = gDuelMiniGameLocalData.m_unOpponentScore;
		return true;
	}
	return false;
}

/**
 * Select player for duel dialog.
 */
class CSelectPlayerForDuelDialog : public CSelectPlayerDialog, public CGameEventListener
{
	DECLARE_CLASS_SIMPLE( CSelectPlayerForDuelDialog, CSelectPlayerDialog );
public:
	CSelectPlayerForDuelDialog( uint64 iItemID );
	virtual ~CSelectPlayerForDuelDialog();
	virtual void OnSelectPlayer( const CSteamID &steamID );
	virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
	virtual void FireGameEvent( IGameEvent *event );

	MESSAGE_FUNC_PARAMS( OnClassIconSelected, "ClassIconSelected", data );
	MESSAGE_FUNC_PARAMS( OnShowClassIconMouseover, "ShowClassIconMouseover", data );
	MESSAGE_FUNC( OnHideClassIconMouseover, "HideClassIconMouseover" );

protected:
	virtual const char *GetResFile() { return "resource/ui/SelectPlayerDialog_Duel.res"; } 
	void SetSelectedClass( int iClass );
	void SetupClassImage( const char *pImageControlName, int iClass );

	uint64 m_iItemID;
	uint8 m_iPlayerClass;
	vgui::Label *m_pClassIconMouseoverLabel;
};

static vgui::DHANDLE< CSelectPlayerForDuelDialog > g_pSelectPlayerForDuelingDialog;

CSelectPlayerForDuelDialog::CSelectPlayerForDuelDialog( uint64 iItemID ) 
	: CSelectPlayerDialog( NULL )
	, m_iItemID( iItemID )
	, m_iPlayerClass( TF_CLASS_UNDEFINED )
{
	g_pSelectPlayerForDuelingDialog = this;
	m_bAllowSameTeam = false;
	m_bAllowOutsideServer = false;
	m_pClassIconMouseoverLabel = new vgui::Label( this, "ClassUsageMouseoverLabel", "" );
	ListenForGameEvent( "teamplay_round_win" );
	ListenForGameEvent( "teamplay_round_stalemate" );
}

CSelectPlayerForDuelDialog::~CSelectPlayerForDuelDialog()
{
	g_pSelectPlayerForDuelingDialog = NULL;
}

void CSelectPlayerForDuelDialog::OnSelectPlayer( const CSteamID &steamID )
{
	GCSDK::CProtoBufMsg<CMsgUseItem> msg( k_EMsgGCUseItemRequest );
	msg.Body().set_item_id( m_iItemID );
	msg.Body().set_target_steam_id( steamID.ConvertToUint64() );
	msg.Body().set_duel__class_lock( m_iPlayerClass );
	GCClientSystem()->BSendMessage( msg );
}

void CSelectPlayerForDuelDialog::ApplySchemeSettings( vgui::IScheme *pScheme )
{
	CSelectPlayerDialog::ApplySchemeSettings( pScheme );
	SetDialogVariable( "title", g_pVGuiLocalize->Find( "TF_DuelDialog_Title" ) );

	SetupClassImage( "ClassUsageImage_Any", TF_CLASS_UNDEFINED );

	C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
	SetupClassImage( "ClassUsageImage_Locked", pLocalPlayer->m_Shared.GetDesiredPlayerClassIndex() );

	SetSelectedClass( TF_CLASS_UNDEFINED );
}

void CSelectPlayerForDuelDialog::SetupClassImage( const char *pImageControlName, int iClass )
{
	CStorePreviewClassIcon *pClassImage = dynamic_cast<CStorePreviewClassIcon*>( FindChildByName( pImageControlName ) );
	if ( pClassImage )
	{
		pClassImage->SetClass( iClass );
	}
}

void CSelectPlayerForDuelDialog::FireGameEvent( IGameEvent *event )
{
	const char *pEventName = event->GetName();

	C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
	if ( pLocalPlayer == NULL )
	{
		OnCommand( "cancel" );
		return;
	}

	if ( Q_strcmp( "teamplay_round_win", pEventName ) == 0 || Q_strcmp( "teamplay_round_stalemate", pEventName ) == 0 )
	{
		OnCommand( "cancel" );
		return;
	}
}

void CSelectPlayerForDuelDialog::OnClassIconSelected( KeyValues *data )
{
	int iClass = data->GetInt( "class", 0 );
	SetSelectedClass( iClass );
}

void CSelectPlayerForDuelDialog::OnHideClassIconMouseover( void )
{
	if ( m_pClassIconMouseoverLabel )
	{
		m_pClassIconMouseoverLabel->SetVisible( false );
	}
}

void CSelectPlayerForDuelDialog::OnShowClassIconMouseover( KeyValues *data )
{
	if ( m_pClassIconMouseoverLabel )
	{
		// Set the text to the correct string
		int iClass = data->GetInt( "class", 0 );
		if ( iClass >= TF_FIRST_NORMAL_CLASS && iClass < TF_LAST_NORMAL_CLASS )
		{
			wchar_t wzLocalized[256];
			const char *pszLocString = "#TF_SelectPlayer_Duel_PlayerClass";
			g_pVGuiLocalize->ConstructString_safe( wzLocalized, g_pVGuiLocalize->Find( pszLocString ), 1, g_pVGuiLocalize->Find( g_aPlayerClassNames[iClass] ) );
			m_pClassIconMouseoverLabel->SetText( wzLocalized );
		}
		else
		{
			const char *pszLocString = "#TF_SelectPlayer_Duel_AnyClass";
			m_pClassIconMouseoverLabel->SetText( pszLocString );
		}

		m_pClassIconMouseoverLabel->SetVisible( true );
	}
}

void CSelectPlayerForDuelDialog::SetSelectedClass( int iClass )
{
	m_iPlayerClass = iClass;

	const char* pClassName = "#TF_SelectPlayer_DuelClass_None";
	
	switch ( m_iPlayerClass )
	{
	case TF_CLASS_SCOUT: 			pClassName = "#TF_Class_Name_Scout"; break;
	case TF_CLASS_SNIPER: 			pClassName = "#TF_Class_Name_Sniper"; break;
	case TF_CLASS_SOLDIER: 			pClassName = "#TF_Class_Name_Soldier"; break;
	case TF_CLASS_DEMOMAN: 			pClassName = "#TF_Class_Name_Demoman"; break;
	case TF_CLASS_MEDIC: 			pClassName = "#TF_Class_Name_Medic"; break;
	case TF_CLASS_HEAVYWEAPONS: 	pClassName = "#TF_Class_Name_HWGuy"; break;
	case TF_CLASS_PYRO: 			pClassName = "#TF_Class_Name_Pyro"; break;
	case TF_CLASS_SPY: 				pClassName = "#TF_Class_Name_Spy"; break;
	case TF_CLASS_ENGINEER: 		pClassName = "#TF_Class_Name_Engineer"; break;
	}

	wchar_t wszText[1024]=L"";
	g_pVGuiLocalize->ConstructString_safe( wszText, 
									  g_pVGuiLocalize->Find( "#TF_SelectPlayer_DuelClass" ),
									  1, 
									  g_pVGuiLocalize->Find( pClassName ) );

	SetDialogVariable( "player_class", wszText );
}

static void ShowSelectDuelTargetDialog( uint64 iItemID )
{
	CSelectPlayerForDuelDialog *pDialog = vgui::SETUP_PANEL( new CSelectPlayerForDuelDialog( iItemID ) );
	pDialog->InvalidateLayout( false, true );

	pDialog->Reset();
	pDialog->SetVisible( true );
	pDialog->MakePopup();
	pDialog->MoveToFront();
	pDialog->SetKeyBoardInputEnabled(true);
	pDialog->SetMouseInputEnabled(true);
	TFModalStack()->PushModal( pDialog );
}

//-----------------------------------------------------------------------------
void CL_Consumables_LevelShutdown()
{
	DuelMiniGame_Reset();
	if ( g_pSelectPlayerForDuelingDialog )
	{
		g_pSelectPlayerForDuelingDialog->OnCommand( "cancel" );
	}
	NotificationQueue_Remove( &CTFDuelRequestNotification::IsDuelRequestNotification );
}

//
// Players see this whenever a person on their server uses a name tool
//
class CTFNameItemNotification : public GCSDK::CGCClientJob
{
public:
	CTFNameItemNotification( GCSDK::CGCClient *pClient ) : GCSDK::CGCClientJob( pClient ) {}
	virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
	{
		GCSDK::CProtoBufMsg<CMsgGCNameItemNotification> msg( pNetPacket );

		if ( steamapicontext == NULL || steamapicontext->SteamUser() == NULL )
			return true;
		
		if ( !engine->IsInGame() )
			return true;

		CBaseHudChat *pHUDChat = (CBaseHudChat *)GET_HUDELEMENT( CHudChat );
		if ( pHUDChat )
		{
			// Player
			wchar_t wszPlayerName[MAX_PLAYER_NAME_LENGTH];
			char szPlayerName[ MAX_PLAYER_NAME_LENGTH ];

			GetPlayerNameBySteamID( msg.Body().player_steamid(), szPlayerName, sizeof( szPlayerName ) );
			g_pVGuiLocalize->ConvertANSIToUnicode( szPlayerName, wszPlayerName, sizeof( wszPlayerName ) );

			// Item
			item_definition_index_t nDefIndex = msg.Body().item_def_index();
			const GameItemDefinition_t *pItemDefinition = dynamic_cast<GameItemDefinition_t *>( GetItemSchema()->GetItemDefinition( nDefIndex ) );
			if ( !pItemDefinition )
				return true;
			entityquality_t iItemQuality = pItemDefinition->GetQuality();

			// Name
			wchar_t wszCustomName[MAX_ITEM_CUSTOM_NAME_LENGTH];
			g_pVGuiLocalize->ConvertANSIToUnicode( msg.Body().item_name_custom().c_str(), wszCustomName, sizeof( wszCustomName ) );

			wchar_t wszItemRenamed[256];
			_snwprintf( wszItemRenamed, ARRAYSIZE( wszItemRenamed ), L"%ls", g_pVGuiLocalize->Find( "#Item_Named" ) );

			const char *pszQualityColorString = EconQuality_GetColorString( (EEconItemQuality)iItemQuality );
			if ( pszQualityColorString )
			{
				pHUDChat->SetCustomColor( pszQualityColorString );
			}
	
			wchar_t wszLocalizedString[256];
			g_pVGuiLocalize->ConstructString_safe( wszLocalizedString, wszItemRenamed, 3, wszPlayerName, CEconItemLocalizedFullNameGenerator( GLocalizationProvider(), pItemDefinition, iItemQuality ).GetFullName(), wszCustomName );

			char szLocalized[256];
			g_pVGuiLocalize->ConvertUnicodeToANSI( wszLocalizedString, szLocalized, sizeof( szLocalized ) );

			pHUDChat->ChatPrintf( 0, CHAT_FILTER_SERVERMSG, "%s", szLocalized );
		}

		return true;
	}
};
GC_REG_JOB( GCSDK::CGCClient, CTFNameItemNotification, "CTFNameItemNotification", k_EMsgGCNameItemNotification, GCSDK::k_EServerTypeGCClient );

//
// A wrapper for a generic message sent down from the GC to clients. The clients do localization
// and layout.
//
class CClientDisplayNotification : public CEconNotification
{
public:
	CClientDisplayNotification( GCSDK::IMsgNetPacket *pNetPacket )
		: m_msg( pNetPacket )
	{
		SetText( m_msg.Body().notification_body_localization_key().c_str() );
		SetLifetime( 23.0f );

		if ( m_msg.Body().body_substring_keys_size() == m_msg.Body().body_substring_values_size() )
		{
			for ( int i = 0; i < m_msg.Body().body_substring_keys_size(); i++ )
			{
				const char *pszSubstringKey = m_msg.Body().body_substring_keys( i ).c_str();
				const char *pszSubstringValue = m_msg.Body().body_substring_values( i ).c_str();

				if ( pszSubstringValue[0] == '#' )
				{
					AddStringToken( pszSubstringKey, GLocalizationProvider()->Find( pszSubstringValue ) );
				}
				else
				{
					CUtlConstWideString wsSubstringValue;
					GLocalizationProvider()->ConvertUTF8ToLocchar( pszSubstringValue, &wsSubstringValue ) ;
					AddStringToken( pszSubstringKey, wsSubstringValue.Get() );
				}
			}
		}
	}

private:
	// We make a local copy of the full message because dynamic-length strings are sent down from the
	// GC and we need to make sure they stay in memory until the user looks at the notification.
	GCSDK::CProtoBufMsg<CMsgGCClientDisplayNotification> m_msg;
};

class CTFClientDisplayNotification : public GCSDK::CGCClientJob
{
public:
	CTFClientDisplayNotification( GCSDK::CGCClient *pClient ) : GCSDK::CGCClientJob( pClient ) {}
	virtual bool BYieldingRunGCJob( GCSDK::IMsgNetPacket *pNetPacket )
	{
		GCSDK::CProtoBufMsg<CMsgGCClientDisplayNotification> msg( pNetPacket );

		if ( steamapicontext == NULL || steamapicontext->SteamUser() == NULL )
			return true;

		NotificationQueue_Add( new CClientDisplayNotification( pNetPacket ) );

		return true;
	}
};
GC_REG_JOB( GCSDK::CGCClient, CTFClientDisplayNotification, "CTFClientDisplayNotification", k_EMsgGCClientDisplayNotification, GCSDK::k_EServerTypeGCClient );