#include "global.h"
#include "ScoreKeeperZero.h"
#include "GameState.h"
#include "PrefsManager.h"
#include "Steps.h"
#include "PrefsManager.h"
#include "ScreenManager.h"
#include "ScreenGameplay.h"
#include "Game.h"
#include "GameManager.h"
#include "GameState.h"
#include "Course.h"
#include "SongManager.h"
#include "NoteDataUtil.h"
#include "RageLog.h"
#include "StageStats.h"
#include "ProfileManager.h"
#include "NetworkSyncManager.h"

ScoreKeeperZero::ScoreKeeperZero( const vector<Song*>& apSongs, const vector<Steps*>& apSteps_, const vector<AttackArray> &asModifiers, PlayerNumber pn_ ):
	ScoreKeeper(pn_), apSteps(apSteps_)
{
	ASSERT( apSongs.size() == apSteps_.size() );
	ASSERT( apSongs.size() == asModifiers.size() );
	//
	// Fill in g_CurStageStats, calculate multiplier
	//
	int iTotalPossibleDancePoints = 0;
	for( unsigned i=0; i<apSteps.size(); i++ )
	{
		Song* pSong = apSongs[i];
		Steps* pSteps = apSteps[i];
		const AttackArray &aa = asModifiers[i];
		NoteData ndTemp;
		pSteps->GetNoteData( &ndTemp );

		/* We might have been given lots of songs; don't keep them in memory uncompressed. */
		pSteps->Compress();

		const Style* pStyle = GAMESTATE->GetCurrentStyle();
		NoteData nd;
		pStyle->GetTransformedNoteDataForStyle( pn_, &ndTemp, &nd );

		/* Compute RadarValues before applying any user-selected mods.  Apply
		 * Course mods and count them in the "pre" RadarValues because they're
		 * forced and not chosen by the user.
		 */
		NoteDataUtil::TransformNoteData( nd, aa, pSteps->m_StepsType, pSong );
		RadarValues rvPre;
		NoteDataUtil::GetRadarValues( nd, pSong->m_fMusicLengthSeconds, rvPre );

		/* Apply user transforms to find out how the notes will really look. 
		 *
		 * XXX: This is brittle: if we end up combining mods for a song differently
		 * than ScreenGameplay, we'll end up with the wrong data.  We should probably
		 * have eg. GAMESTATE->GetOptionsForCourse(po,so,pn) to get options based on
		 * the last call to StoreSelectedOptions and the modifiers list, but that'd
		 * mean moving the queues in ScreenGameplay to GameState ... */
		NoteDataUtil::TransformNoteData( nd, GAMESTATE->m_PlayerOptions[pn_], pSteps->m_StepsType );
		RadarValues rvPost;
		NoteDataUtil::GetRadarValues( nd, pSong->m_fMusicLengthSeconds, rvPost );
		 
		iTotalPossibleDancePoints += this->GetPossibleDancePoints( rvPre, rvPost );
	}
	g_CurStageStats.iPossibleDancePoints[pn_] = iTotalPossibleDancePoints;


	m_iCurCombo = 0; 
}

void ScoreKeeperZero::OnNextSong( int iSongInCourseIndex, const Steps* pSteps, const NoteData* pNoteData )
{
/*
  http://www.aaroninjapan.com/ddr2.html

  Note on NONSTOP Mode scoring

  Nonstop mode requires the player to play 4 songs in succession, with the total maximum possible score for the four song set being 100,000,000. This comes from the sum of the four stages' maximum possible scores, which, regardless of song or difficulty is: 

  10,000,000 for the first song
  20,000,000 for the second song
  30,000,000 for the third song
  40,000,000 for the fourth song

  We extend this to work with nonstop courses of any length.

  We also keep track of this scoring type in endless, with 100mil per iteration
  of all songs, though this score isn't actually seen anywhere right now.
*/
	m_iCurCombo = 0;

	if ( GAMESTATE->GetCurrentGame() == &g_Games[GAME_PUMP] )
	{
		Steps* pSteps = GAMESTATE->m_pCurSteps[ GAMESTATE->GetFirstHumanPlayer() ];
		ASSERT( pSteps );

		StepsType st = pSteps->m_StepsType;

		if ( st == STEPS_TYPE_PUMP_DOUBLE &&
		     pSteps->GetDifficulty() == DIFFICULTY_HARD)
		{
			FOREACH_EnabledPlayer(p)
			{
				int &iScore = g_CurStageStats.iScore[p];
				iScore += 500000;
			}
		}
	}
}

void ScoreKeeperZero::AddScore( TapNoteScore score, int iNumTapsInRow, bool isPureHold )
{
	int &iScore = g_CurStageStats.iScore[m_PlayerNumber];

	int p;

	switch( score )
	{
	case TNS_MARVELOUS:
	case TNS_PERFECT:
		p = 1000;
		break;
	case TNS_GREAT:
		p = 500;
		break;
	case TNS_GOOD:
		p = 100;
		break;
	case TNS_BOO:
		p = -200;
		break;
	case TNS_MISS:
		if( isPureHold )
			p = -300;
		else
			p = -500;
		break;
	default:
		ASSERT(0);
		p = 0;
		break;
	}

	if( m_iCurCombo >= 50 )
	{
		switch( score )
		{
		case TNS_MARVELOUS:
		case TNS_PERFECT:
		case TNS_GREAT:
			p += 1000;
			break;
		default:
			break;
		}
	}

	if( iNumTapsInRow == 3 )
		p += (p / 2);
	else if( iNumTapsInRow > 3 )
		p += p;

	iScore += p;

	if( iScore < 0 )
		iScore = 0;
	//ASSERT( iScore >= 0 );

	printf( "score: %i\n", iScore );
}

void ScoreKeeperZero::HandleTapScore( TapNoteScore score )
{
	if( score == TNS_HIT_MINE )
	{
		if( GAMESTATE->m_HealthState[m_PlayerNumber] != GameState::DEAD )
			g_CurStageStats.iActualDancePoints[m_PlayerNumber] += TapNoteScoreToDancePoints( TNS_HIT_MINE );
		g_CurStageStats.iTapNoteScores[m_PlayerNumber][TNS_HIT_MINE] += 1;
	}
}

void ScoreKeeperZero::HandleTapRowScore( TapNoteScore rowScore, int iNumTapsInRow, bool bHold )
{
	ASSERT( iNumTapsInRow >= 1 );

	// Update dance points.
	if( GAMESTATE->m_HealthState[m_PlayerNumber] != GameState::DEAD )
		g_CurStageStats.iActualDancePoints[m_PlayerNumber] += TapNoteScoreToDancePoints( rowScore );
	// update judged row totals
	g_CurStageStats.iTapNoteScores[m_PlayerNumber][rowScore] += 1;

	//
	// Regular combo
	//
	
/*
  http://www.aaroninjapan.com/ddr2.html

  Note on ONI Mode scoring
  
  Your combo counter only increased with a "Marvelous/Perfect", and double Marvelous/Perfect steps (left and right, etc.)
  only add 1 to your combo instead of 2. The combo counter thus becomes a "Marvelous/Perfect" counter. 
*/
	/* True if a jump is one to combo, false if combo is purely based on tap count. */
	bool ComboIsPerRow = true;
	switch( PREFSMAN->m_iScoringType )
	{
	case PrefsManager::SCORING_ZERO:
		ComboIsPerRow = (GAMESTATE->m_PlayMode == PLAY_MODE_ONI);
		break;
	default:
		ASSERT(0);
	}

	if ( GAMESTATE->GetCurrentGame() == &g_Games[GAME_PUMP] )
		ComboIsPerRow = true;

	const int ComboCountIfHit = ComboIsPerRow? 1: iNumTapsInRow;
	TapNoteScore MinScoreToContinueCombo = GAMESTATE->m_PlayMode == PLAY_MODE_ONI? TNS_PERFECT:TNS_GREAT;

	if( rowScore >= MinScoreToContinueCombo )
		g_CurStageStats.iCurCombo[m_PlayerNumber] += ComboCountIfHit;

	AddScore( rowScore, iNumTapsInRow, bHold );		// only score once per row

	//
	// handle combo logic
	//
#ifndef DEBUG
	if( PREFSMAN->m_bAutoPlay && !GAMESTATE->m_bDemonstrationOrJukebox )	// cheaters never prosper
	{
		m_iCurCombo = 0;
		return;
	}
#endif //DEBUG

	//
	// Toasty combo
	//
	switch( rowScore )
	{
	case TNS_MARVELOUS:
	case TNS_PERFECT:
	case TNS_GREAT:
		m_iCurCombo += iNumTapsInRow;

		if( m_iCurCombo >= 250 &&
			m_iCurCombo - iNumTapsInRow < 250 &&
			!GAMESTATE->m_bDemonstrationOrJukebox )
		{
			SCREENMAN->PostMessageToTopScreen( SM_PlayToasty, 0 );
			PROFILEMAN->IncrementToastiesCount( m_PlayerNumber );
		}
		break;
	case TNS_GOOD:
		if ( GAMESTATE->GetCurrentGame() == &g_Games[GAME_PUMP] )
			break; // do nothing with combo
		// fallthrough
	default:
		m_iCurCombo = 0;
		break;
	}

	
	NSMAN->ReportScore(m_PlayerNumber, rowScore,
                       g_CurStageStats.iScore[m_PlayerNumber],
                       g_CurStageStats.iCurCombo[m_PlayerNumber]);
}


void ScoreKeeperZero::HandleHoldScore( HoldNoteScore holdScore, TapNoteScore tapScore )
{
	// update dance points totals
	if( GAMESTATE->m_HealthState[m_PlayerNumber] != GameState::DEAD )
		g_CurStageStats.iActualDancePoints[m_PlayerNumber] += HoldNoteScoreToDancePoints( holdScore );
	g_CurStageStats.iHoldNoteScores[m_PlayerNumber][holdScore] ++;

	//if( holdScore == HNS_OK )
	//	AddScore( TNS_MARVELOUS, 1 );

	NSMAN->ReportScore(m_PlayerNumber, holdScore+7, 
                       g_CurStageStats.iScore[m_PlayerNumber],
                       g_CurStageStats.iCurCombo[m_PlayerNumber]);
}


int ScoreKeeperZero::GetPossibleDancePoints( const RadarValues& radars )
{
	/* Note that, if Marvelous timing is disabled or not active (not course mode),
	 * PERFECT will be used instead. */

	int NumTaps = int(radars[RADAR_NUM_TAPS_AND_HOLDS]);
	int NumHolds = int(radars[RADAR_NUM_HOLDS]); 
	return NumTaps*TapNoteScoreToDancePoints(TNS_MARVELOUS)+
	   NumHolds*HoldNoteScoreToDancePoints(HNS_OK);
}

int ScoreKeeperZero::GetPossibleDancePoints( const RadarValues& fOriginalRadars, const RadarValues& fPostRadars )
{
	/*
	 * The logic here is that if you use a modifier that adds notes, you should have to
	 * hit the new notes to get a high grade.  However, if you use one that removes notes,
	 * they should simply be counted as misses. */
	return max( 
		GetPossibleDancePoints(fOriginalRadars),
		GetPossibleDancePoints(fPostRadars) );
}


int ScoreKeeperZero::TapNoteScoreToDancePoints( TapNoteScore tns )
{
	if( !GAMESTATE->ShowMarvelous() && tns == TNS_MARVELOUS )
		tns = TNS_PERFECT;

/*
  http://www.aaroninjapan.com/ddr2.html

  Note on ONI Mode scoring

  The total number of Dance Points is calculated with Marvelous steps being worth 3 points, Perfects getting 
  2 points, OKs getting 3 points, Greats getting 1 point, and everything else is worth 0 points. (Note: The 

*/

	/* This is used for Oni percentage displays.  Grading values are currently in
	 * StageStats::GetGrade. */
	switch( tns )
	{
	case TNS_NONE:		return 0;
	case TNS_HIT_MINE:	return PREFSMAN->m_iPercentScoreWeightHitMine;
	case TNS_MISS:		return PREFSMAN->m_iPercentScoreWeightMiss;
	case TNS_BOO:		return PREFSMAN->m_iPercentScoreWeightBoo;
	case TNS_GOOD:		return PREFSMAN->m_iPercentScoreWeightGood;
	case TNS_GREAT:		return PREFSMAN->m_iPercentScoreWeightGreat;
	case TNS_PERFECT:	return PREFSMAN->m_iPercentScoreWeightPerfect;
	case TNS_MARVELOUS:	return PREFSMAN->m_iPercentScoreWeightMarvelous;
	default: FAIL_M( ssprintf("%i", tns) );
	}
}

int ScoreKeeperZero::HoldNoteScoreToDancePoints( HoldNoteScore hns )
{
	switch( hns )
	{
	case HNS_NONE: return 0;
	case HNS_NG: return PREFSMAN->m_iPercentScoreWeightNG;
	case HNS_OK: return PREFSMAN->m_iPercentScoreWeightOK;
	default: FAIL_M( ssprintf("%i", hns) );
	}
}

/*
 * (c) 2001-2004 Chris Danford, Glenn Maynard
 * All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, and/or sell copies of the Software, and to permit persons to
 * whom the Software is furnished to do so, provided that the above
 * copyright notice(s) and this permission notice appear in all copies of
 * the Software and that both the above copyright notice(s) and this
 * permission notice appear in supporting documentation.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
 * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
 * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
 * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
 * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */
