// Count how many achievements have been earned in our range
void CAchievement_AchievedCount::OnSteamUserStatsStored( void )
{
	int iAllAchievements = m_pAchievementMgr->GetAchievementCount();
	int iAchieved = 0;

	for ( int i=0; i<iAllAchievements; ++i )
	{		
		IAchievement* pCurAchievement = (IAchievement*)m_pAchievementMgr->GetAchievementByIndex( i );
		Assert ( pCurAchievement );

		int iAchievementID = pCurAchievement->GetAchievementID();
		if ( iAchievementID < m_iLowRange || iAchievementID > m_iHighRange )
			continue;

		if ( pCurAchievement->IsAchieved() )
		{
			iAchieved++;
		}
	}

	if ( iAchieved >= m_iNumRequired )
	{
		IncrementCount();
	}
}
//----------------------------------------------------------
// Query the system interface for this game's list of achievements
//----------------------------------------------------------
void CAchievementsDialog_XBox::ApplySettings( KeyValues *pResourceData )
{
	BaseClass::ApplySettings( pResourceData );

	m_bCenterOnScreen = pResourceData->GetInt( "center", 1 ) == 1;

	if ( !achievementmgr )
	{
		AssertOnce( 0 && "No achievement manager interface in GameUI.dll" );
		return;
	}

	achievementmgr->EnsureGlobalStateLoaded();

	int iAllAchievements = achievementmgr->GetAchievementCount();
	
	for ( int i = 0; i < iAllAchievements; ++i )
	{		
		IAchievement* pCurAchievement = (IAchievement*)achievementmgr->GetAchievementByIndex( i );
		Assert ( pCurAchievement );

		if ( pCurAchievement->IsAchieved() )
			++m_nUnlocked;

		// don't show hidden achievements if not achieved
		if ( pCurAchievement->ShouldHideUntilAchieved() && !pCurAchievement->IsAchieved() )
			continue;

		CAchievementItem *pItem = m_Menu.AddAchievementItem(  ACHIEVEMENT_LOCALIZED_NAME( pCurAchievement ), 
									ACHIEVEMENT_LOCALIZED_DESC( pCurAchievement ), 
									pCurAchievement->GetPointValue(),
									pCurAchievement->IsAchieved(),
									pCurAchievement
									);

		SETUP_PANEL( pItem );
	}

	m_nTotalAchievements = m_Menu.GetItemCount();
}
//----------------------------------------------------------
// New group was selected in the dropdown, recalc what achievements to show
//----------------------------------------------------------
void CAchievementsDialog::OnTextChanged(KeyValues *data)
{
	Panel *pPanel = (Panel *)data->GetPtr( "panel", NULL );

	// first check which control had its text changed!
	if ( pPanel == m_pAchievementPackCombo )
	{
		// Re-populate the achievement list with the selected group

		m_pAchievementsList->DeleteAllItems();

		KeyValues *pData = m_pAchievementPackCombo->GetActiveItemUserData();

		if ( pData )
		{
			int iMinRange = pData->GetInt( "minrange" );
			int iMaxRange = pData->GetInt( "maxrange" );

			if ( achievementmgr )
			{
				int iCount = achievementmgr->GetAchievementCount();
				for ( int i = 0; i < iCount; ++i )
				{		
					IAchievement* pCur = achievementmgr->GetAchievementByIndex( i );

					if ( !pCur )
						continue;
					
					int iAchievementID = pCur->GetAchievementID();

					if ( iAchievementID < iMinRange || iAchievementID > iMaxRange )
						continue;

					// don't show hidden achievements if not achieved
					if ( pCur->ShouldHideUntilAchieved() && !pCur->IsAchieved() )
						continue;

					CAchievementDialogItemPanel *achievementItemPanel = new CAchievementDialogItemPanel( m_pAchievementsList, "AchievementDialogItemPanel", i );
					achievementItemPanel->SetAchievementInfo( pCur );
					m_pAchievementsList->AddItem( NULL, achievementItemPanel );
				}
			}
		}

		m_pAchievementsList->ScrollToItem( 0 );
	}
}
//=============================================================================
void Achievements::Activate()
{
	BaseClass::Activate();

	// Populate the achievements list.
	m_GplAchievements->RemoveAllPanelItems();

	if ( !achievementmgr )
		return;

	m_iAwardCompleteCount = 0;
	m_iAchCompleteCount = 0;
	int incompleteCount= 0;
	int gamerScore = 0;

	//
	// Add the "Achieved" ones
	//
	for(int i = 0; i < achievementmgr->GetAchievementCount(); i++)
	{
		IAchievement* achievement = achievementmgr->GetAchievementByDisplayOrder( i, m_iStartingUserSlot );

		if ( achievement && achievement->IsAchieved() )
		{
			AchievementListItem *panelItem = new AchievementListItem( achievement );
			if ( panelItem )
			{
				m_GplAchievements->AddPanelItem( panelItem, true );
			}

			gamerScore += achievement->GetPointValue();
			++m_iAchCompleteCount;
		}
	}

	//
	// Add the "Unattained" ones
	//
	for(int i = 0; i < achievementmgr->GetAchievementCount(); i++)
	{
		IAchievement* achievement = achievementmgr->GetAchievementByDisplayOrder( i, m_iStartingUserSlot );

		if ( achievement && !achievement->IsAchieved() )
		{
			AchievementListItem *panelItem = new AchievementListItem( achievement );
			if ( panelItem )
			{
				m_GplAchievements->AddPanelItem( panelItem, true );
			}

			++incompleteCount;
		}
	} 

	// Populate the awards list.
	int awardIncompleteCount= 0;
	if ( IsX360() )
	{
		m_GplAwards->RemoveAllPanelItems();

		for ( int i = 0; i < achievementmgr->GetAchievementCount(); i++ )
		{
			IAchievement* achievement = achievementmgr->GetAchievementByIndex( i, m_iStartingUserSlot );
			if ( achievement && achievement->IsAchieved() )
			{
				AchievementListItem *panelItem = new AchievementListItem( achievement );
				if ( panelItem )
				{
					m_GplAchievements->AddPanelItem( panelItem, true );
				}

				gamerScore += achievement->GetPointValue();
				++m_iAwardCompleteCount;
			}
		}

		for( int i = 0; i < achievementmgr->GetAchievementCount(); i++ )
		{
			IAchievement* achievement = achievementmgr->GetAchievementByIndex( i, m_iStartingUserSlot );
			if ( achievement && !achievement->IsAchieved() )
			{
				AchievementListItem *panelItem = new AchievementListItem( achievement );
				if ( panelItem )
				{
					m_GplAchievements->AddPanelItem( panelItem, true );
				}

				++awardIncompleteCount;
			}
		} 
	}
	if ( m_GplAwards )
	{
		m_GplAwards->SetVisible( false );
	}

	//
	// Update achievement and gamerscore progress
	//
	wchar_t localizedGamerscoreProgress[128]; 
	char buffer[64];
	wchar_t wNumAchieved[64];
	wchar_t wTotalAchievements[64];
	wchar_t wGamerscore[64];

	// Construct achievement progress string
	itoa( achievementmgr->GetAchievementCount(), buffer, 10 );
	V_UTF8ToUnicode( buffer, wTotalAchievements, sizeof( wNumAchieved ) );
	itoa( m_iAchCompleteCount, buffer, 10 );
	V_UTF8ToUnicode( buffer, wNumAchieved, sizeof( wTotalAchievements ) );
	g_pVGuiLocalize->ConstructString( m_wAchievementsProgress, sizeof( m_wAchievementsProgress ), g_pVGuiLocalize->Find( "#L4D360UI_Achievement_Progress" ), 2, wNumAchieved, wTotalAchievements );
	m_LblComplete->SetText( m_wAchievementsProgress );

	// Construct gamerscore progress string
	itoa( gamerScore, buffer, 10 );
	V_UTF8ToUnicode( buffer, wGamerscore, sizeof( wGamerscore ) );
	g_pVGuiLocalize->ConstructString( localizedGamerscoreProgress, sizeof( localizedGamerscoreProgress ), g_pVGuiLocalize->Find( "#L4D360UI_Gamerscore_Progress" ), 2, wGamerscore );
	m_LblGamerscore->SetText( localizedGamerscoreProgress );

	// Focus on the first item in the list
	m_GplAchievements->NavigateTo();
	m_GplAchievements->SelectPanelItem( 0 );

	// Set the progress bar
	m_flTotalProgress = static_cast<float>(m_iAchCompleteCount) / static_cast<float>(achievementmgr->GetAchievementCount());

	UpdateFooter();

	ToggleDisplayType( m_bShowingAssets );
}
//-----------------------------------------------------------------------------
// Purpose: creates child panels, passes down name to pick up any settings from res files.
//-----------------------------------------------------------------------------
CAchievementsDialog::CAchievementsDialog(vgui::Panel *parent) : BaseClass(parent, "AchievementsDialog")
{
	SetDeleteSelfOnClose(true);
	SetBounds(0, 0, 512, 384);
	SetMinimumSize( 256, 300 );
	SetSizeable( true );

	m_nUnlocked = 0;

	m_pAchievementsList = new vgui::PanelListPanel( this, "listpanel_achievements" );
	m_pAchievementsList->SetFirstColumnWidth( 0 );

	m_pListBG = new vgui::ImagePanel( this, "listpanel_background" );

	m_pPercentageBarBackground = SETUP_PANEL( new ImagePanel( this, "PercentageBarBackground" ) );
	m_pPercentageBar = SETUP_PANEL( new ImagePanel( this, "PercentageBar" ) );

	m_pAchievementPackCombo = new ComboBox(this, "achievement_pack_combo", 10, false);

	// int that holds the highest number achievement id we've found
	int iHighestAchievementIDSeen = -1;
	int iNextGroupBoundary = 1000;

	Q_memset( m_AchievementGroups, 0, sizeof(m_AchievementGroups) );
	m_iNumAchievementGroups = 0;

	// Base groups
	CreateNewAchievementGroup( 0, 16000 );
	CreateNewAchievementGroup( 0, 999 );

	Assert ( achievementmgr );
	if ( achievementmgr )
	{
		int iCount = achievementmgr->GetAchievementCount();
		for ( int i = 0; i < iCount; ++i )
		{		
			IAchievement* pCur = achievementmgr->GetAchievementByIndex( i );

			if ( !pCur )
				continue;

			int iAchievementID = pCur->GetAchievementID();

			if ( iAchievementID > iHighestAchievementIDSeen )
			{
				// if its crossed the next group boundary, create a new group
				if ( iAchievementID >= iNextGroupBoundary )
				{
					int iNewGroupBoundary = 100 * ( (int)( (float)iAchievementID / 100 ) );
					CreateNewAchievementGroup( iNewGroupBoundary, iNewGroupBoundary+99 );

					iNextGroupBoundary = iNewGroupBoundary + 100;
				}

				iHighestAchievementIDSeen = iAchievementID;
			}

			// don't show hidden achievements if not achieved
			if ( pCur->ShouldHideUntilAchieved() && !pCur->IsAchieved() )
				continue;

			bool bAchieved = pCur->IsAchieved();

			if ( bAchieved )
			{
				++m_nUnlocked;
			}

			for ( int j=0;j<m_iNumAchievementGroups;j++ )
			{
				if ( iAchievementID >= m_AchievementGroups[j].m_iMinRange &&
					iAchievementID <= m_AchievementGroups[j].m_iMaxRange )
				{
					if ( bAchieved )
					{
						m_AchievementGroups[j].m_iNumUnlocked++;
					}

					m_AchievementGroups[j].m_iNumAchievements++;
				}
			}
			
			CAchievementDialogItemPanel *achievementItemPanel = new CAchievementDialogItemPanel( m_pAchievementsList, "AchievementDialogItemPanel", i );
			achievementItemPanel->SetAchievementInfo( pCur );
			m_pAchievementsList->AddItem( NULL, achievementItemPanel );
		}
	}


	for ( int i=0;i<m_iNumAchievementGroups;i++ )
	{
		char buf[128];

		if ( i == 0 )
		{
			Q_snprintf( buf, sizeof(buf), "#Achievement_Group_All" );
		}
		else
		{
			Q_snprintf( buf, sizeof(buf), "#Achievement_Group_%d", m_AchievementGroups[i].m_iMinRange );
		}		

		wchar_t *wzGroupName = g_pVGuiLocalize->Find( buf );

		if ( !wzGroupName )
		{
			wzGroupName = L"Need Title ( %s1 of %s2 )";
		}

		wchar_t wzGroupTitle[128];

		if ( wzGroupName )
		{
			wchar_t wzNumUnlocked[8];
			_itow_s( m_AchievementGroups[i].m_iNumUnlocked, wzNumUnlocked, ARRAYSIZE( wzNumUnlocked ), 10 );

			wchar_t wzNumAchievements[8];
			_itow_s( m_AchievementGroups[i].m_iNumAchievements, wzNumAchievements, ARRAYSIZE( wzNumAchievements ), 10 );

			g_pVGuiLocalize->ConstructString( wzGroupTitle, sizeof( wzGroupTitle ), wzGroupName, 2, wzNumUnlocked, wzNumAchievements );
		}

		KeyValues *pKV = new KeyValues( "grp" );
		pKV->SetInt( "minrange", m_AchievementGroups[i].m_iMinRange );
		pKV->SetInt( "maxrange", m_AchievementGroups[i].m_iMaxRange );
		m_pAchievementPackCombo->AddItem( wzGroupTitle, pKV );
	}

	m_pAchievementPackCombo->ActivateItemByRow( 0 );
}