//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop

#include "GlobalUnit.h"
#include "ProgressThreadUnit.h";
#include "ProgressFormUnit.h"
#include "Project.h"
#include "MidiTrack.h"

#define OPERATION_MM_SAVE				1
#define OPERATION_MM_LOAD				2
#define OPERATION_PROJ_LOAD				3
#define OPERATION_PROJ_SAVE				4
#define OPERATION_USER_LOGIN			5
#define OPERATION_USER_CHECKPAYMENT		6
#define OPERATION_USER_CONFIRMPAYMENT 	7
#define OPERATION_USER_SUBMITQA			8
#define OPERATION_USER_REGISTER			9
#define OPERATION_USER_UPLOADSONG		10
#define OPERATION_USER_SUBMITSCORE		11
#define OPERATION_USER_UPLOADSTYLE		12
#define OPERATION_MM_FXAPPLY			13
#define OPERATION_MM_SAVEMEDIA			14

#define STATE_IDLE  					0x00
#define STATE_SAVING	                0x01
#define STATE_SAVE_SUCCESS              0x02
#define STATE_SAVE_FAILED               0x04
#define STATE_CONFIRMING               	0x10
#define STATE_CONFIRM_SUCCESS           0x20
#define STATE_CONFIRM_FAILED           	0x40

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "PNGButton"
#pragma link "GeneralDialogPanel"
#pragma resource "*.dfm"
TProgressForm *ProgressForm;

//---------------------------------------------------------------------------
__fastcall TProgressForm::TProgressForm(TComponent* Owner)
	: TForm(Owner)
{
	SetTransparent( this );

	m_nMaxPos = m_pbProgress->Width;
	m_nPos = 0;

	m_nParam1 = m_nParam2 = m_nParam3 = m_nParam4 = 0;
	m_dblParam1 = m_dblParam2 = 0;
	m_pParam1 = m_pParam2 = NULL;
	m_pIntParam1 = m_pIntParam2 = NULL;
	memset( m_strParam1, 0, sizeof(m_strParam1) );
	memset( m_strBuff, 0, sizeof(m_strBuff) );

	m_bmpTileLeft = new TBitmap();
	m_bmpTileLeft->LoadFromResourceName(int(HInstance), L"imgProgressLeft");
	m_bmpTileRight = new TBitmap();
	m_bmpTileRight->LoadFromResourceName(int(HInstance), L"imgProgressRight");

	m_nTileWidth = m_bmpTileLeft->Width;
	m_nTileHeight = m_bmpTileLeft->Height;

	m_nNextMinPos = 0;
	m_nNextMaxPos = m_nMaxPos;
	m_iOperation = m_iOperationResult = 0;

	m_pConfirmThread = NULL;
	m_iSaveState = STATE_IDLE;
	m_iConfirmResult = m_iFileHandle = 0;

	m_pTimer = new TTimer(this);
	m_pTimer->Enabled = false;
	m_pTimer->Interval = 200;
	m_pTimer->OnTimer = TimerProc;

	m_pThread = new TProgressThread( true, this );
}
//---------------------------------------------------------------------------

__fastcall TProgressForm::~TProgressForm()
{
	if( m_pThread )
		delete m_pThread;

	if( m_pConfirmThread )
		delete m_pConfirmThread;

	if( m_bmpTileLeft )
		delete m_bmpTileLeft;

	if( m_bmpTileRight )
		delete m_bmpTileRight;

	if( m_pTimer ){
		delete m_pTimer;
	}
}
//---------------------------------------------------------------------------

void __fastcall TProgressForm::ProgressPaint(TObject *Sender)
{
	int x = 0;
	//左侧平铺
	if( m_nPos>0 ){
		for( int i=0; i<m_nPos/m_nTileWidth+1; i++ ){
			m_pbProgress->Canvas->Draw( x+m_nTileWidth*i, 0, m_bmpTileLeft );
		}
		x += m_nTileWidth;
	}

	//右侧平铺
	x = m_nPos;
	if( m_nPos<m_nMaxPos ){
		for( int i=0; i<(m_nMaxPos-m_nPos)/m_nTileWidth+1; i++ ){
			m_pbProgress->Canvas->Draw( x+m_nTileWidth*i, 0, m_bmpTileRight );
		}
		x += m_nTileWidth;
	}

	// 左外边框线
	m_pbProgress->Canvas->Pen->Color = TColor(0x83807D);
    m_pbProgress->Canvas->MoveTo(0, 1);
    m_pbProgress->Canvas->LineTo(0, 19);

    // 左内边框线
    m_pbProgress->Canvas->Pen->Color = TColor(0x1B1816);
	m_pbProgress->Canvas->MoveTo(1, 1);
	m_pbProgress->Canvas->LineTo(1, 19);

	// 右内边框线
	m_pbProgress->Canvas->Pen->Color = TColor(0x1B1816);
	m_pbProgress->Canvas->MoveTo(m_pbProgress->Width - 2, 1);
	m_pbProgress->Canvas->LineTo(m_pbProgress->Width - 2, 19);

    // 右外边框线
    m_pbProgress->Canvas->Pen->Color = TColor(0x83807D);
	m_pbProgress->Canvas->MoveTo(m_pbProgress->Width - 1, 1);
    m_pbProgress->Canvas->LineTo(m_pbProgress->Width - 1, 19);
}
//---------------------------------------------------------------------------

void __fastcall TProgressForm::UMOperateFailed(TMessage &Message)
{
	m_pThread->WaitFor();// >Terminate();
	m_iOperationResult = Message.WParam;

	if( m_iOperation==OPERATION_MM_SAVEMEDIA ){
		m_iSaveState &= ~STATE_SAVING;
		m_iSaveState |= STATE_SAVE_FAILED;
	}

	Canceled();
//	ModalResult = mrCancel;
}
//---------------------------------------------------------------------------

void __fastcall TProgressForm::UMOperatePercent(TMessage &Message)
{
	TRect rcRedraw( m_nPos, 0, m_nMaxPos, m_nTileHeight );

	m_nPos = m_nNextMinPos + Message.WParam * (m_nNextMaxPos - m_nNextMinPos) / 100;
	rcRedraw.right = m_nPos;

	InvalidateRect( m_panelProgress->Handle, &rcRedraw, false );

/*	if( m_iOperation==OPERATION_MM_SAVEMEDIA ){
		if( m_iSaveState<STATE_CONFIRMING && Message.WParam>95 ){
			StartConfirm();
		}
	}
*/
}
//---------------------------------------------------------------------------

void __fastcall TProgressForm::UMOperateComplete(TMessage &Message)
{
	m_pThread->WaitFor();// >Terminate();
	m_iOperationResult = Message.WParam;

	if( m_iOperation==OPERATION_MM_SAVEMEDIA ){
		m_iSaveState &= ~STATE_SAVING;
		m_iSaveState |= STATE_SAVE_SUCCESS;

		if( m_iSaveState & STATE_CONFIRM_SUCCESS ){
			ModalResult = mrOk;
		}
		else{
			if( m_iFileHandle==0 && FileExists(m_strParam1) ){
				m_iFileHandle = FileOpen( m_strParam1, fmOpenRead|fmShareExclusive );
			}

			if( m_iSaveState<STATE_CONFIRMING )
				StartConfirm();
		}
	}
	else{
		ModalResult = mrOk;
	}
}
//---------------------------------------------------------------------------

void __fastcall TProgressForm::UMOperateNextRange(TMessage &Message)
{
	m_nNextMinPos = Message.WParam * m_nMaxPos / 100;
	m_nNextMaxPos = ( Message.LParam==0 ? m_nMaxPos : Message.LParam * m_nMaxPos / 100 );
}
//---------------------------------------------------------------------------

void __fastcall TProgressForm::UMRecordComplete(TMessage &Message)
{
	m_MsgTransparent = Message;
	m_pThread->WaitFor();
//	m_pThread->Terminate();

	ModalResult = mrOk;
}
//---------------------------------------------------------------------------

void __fastcall TProgressForm::UMPaymentConfirmed(TMessage &Message)
{
	m_pTimer->Enabled = false;
	m_pConfirmThread->WaitFor();
//	m_pConfirmThread->Terminate();

	m_iSaveState &= ~STATE_CONFIRMING;

	if( m_iConfirmResult==0 ){
		m_iSaveState |= STATE_CONFIRM_SUCCESS;

		if( m_iSaveState & STATE_SAVE_SUCCESS ){
			if( m_iFileHandle>0 ){
				FileClose( m_iFileHandle );
				m_iFileHandle = 0;
			}

			ModalResult = mrOk;
		}
		else if( m_iSaveState & STATE_SAVE_FAILED )
			Canceled();

		DebugPrint( "Payment confirmed.\n" );
	}
	else{
		m_iSaveState |= STATE_CONFIRM_FAILED;
		m_iOperationResult = m_iConfirmResult;

		//ModalResult = mrCancel;
		Canceled();
	}
}
//---------------------------------------------------------------------------

void TProgressForm::StartConfirm()
{
	if( m_iSaveState<STATE_CONFIRMING ){
		m_iSaveState |= STATE_CONFIRMING;
		m_pTimer->Interval = 60000; //1分钟
		m_pTimer->Enabled = true;

		m_pConfirmThread = new TProgressThread( true, this );
		m_pConfirmThread->Start();

		DebugPrint( "Start confirm thread.\n" );
	}
}
//---------------------------------------------------------------------------

void __fastcall TProgressForm::FormCreate(TObject *Sender)
{
	m_DialogPanel->Font->Size = g_szFont9;

	// TForm 位置居中
	TPoint mfPoint = Application->MainForm->ClientToScreen(TPoint(0, 0));

	int mfHeight = Application->MainForm->Height;
	int mfWidth = Application->MainForm->Width;

	Top = (mfHeight - Height) / 2 + mfPoint.Y;
	Left = (mfWidth - Width) / 2 + mfPoint.X;

	// 进度条框圆角
	HRGN hRgn = CreateRoundRectRgn( 0, 0, m_panelProgress->Width+1,
									m_panelProgress->Height+1, 3, 3 );
	SetWindowRgn( m_panelProgress->Handle, hRgn, false );
	DeleteObject( hRgn );
}
//---------------------------------------------------------------------------

int __fastcall TProgressForm::MM_SaveMedia( int iSaveType, int iFileType, LPCTSTR strFileName,
													int iOp, int nIdCount, UINT aIdStyle[] )
{
	wcscpy( m_strParam1, strFileName );
	if( iSaveType==0 ){
	   iSaveType = SAVE_COMPOSE | SAVE_AUDIO;
	   m_DialogPanel->Caption = L"正在生成歌曲";
	}
	else{
	   m_DialogPanel->Caption = L"正在保存";
	}

	m_nParam1 = iFileType;
	m_nParam2 = iSaveType;
	m_nParam3 = nIdCount;
	m_nParam4 = iOp;
	m_pParam1 = aIdStyle;

	m_iOperation = OPERATION_MM_SAVEMEDIA;
	m_pThread->Start();

	return ShowModal();
}
//---------------------------------------------------------------------------

int __fastcall TProgressForm::MM_Load( LPCTSTR strFileName, int iFileType )
{
	wcscpy( m_strParam1, strFileName );
	m_iOperation = OPERATION_MM_LOAD;
	m_nParam1 = iFileType;

	m_DialogPanel->Caption = L"正在处理";

	m_pThread->Start();

	return ShowModal();
}
//---------------------------------------------------------------------------

int __fastcall TProgressForm::MM_AudioFxApply( double dblBegin, double dblEnd )
{
	m_dblParam1 = dblBegin;
	m_dblParam2 = dblEnd;
	m_iOperation = OPERATION_MM_FXAPPLY;
	m_DialogPanel->Caption = L"正在处理";

	m_pThread->Start();

	return ShowModal();
}

int __fastcall TProgressForm::Project_Save( LPCTSTR strFileName )
{
	wcscpy( m_strParam1, strFileName );
	m_iOperation = OPERATION_PROJ_SAVE;
	m_DialogPanel->Caption = L"正在保存";
	m_pThread->Start();

	return ShowModal();
}
//---------------------------------------------------------------------------

int __fastcall TProgressForm::Project_Load( LPCTSTR strFileName )
{
	wcscpy( m_strParam1, strFileName );
	m_iOperation = OPERATION_PROJ_LOAD;
	m_DialogPanel->Caption = L"正在打开";
	m_pThread->Start();

	return ShowModal();
}
//---------------------------------------------------------------------------

int __fastcall TProgressForm::User_Login()
{
	m_iOperation = OPERATION_USER_LOGIN;
	m_DialogPanel->Caption = L"正在登录";
	m_pTimer->Enabled = true;
	m_pThread->Start();

	return ShowModal();
}
//---------------------------------------------------------------------------

int __fastcall TProgressForm::User_Register( int isEmailOrMobile )
{
    m_nParam1 = isEmailOrMobile;
	m_iOperation = OPERATION_USER_REGISTER;
	m_DialogPanel->Caption = L"正在注册";
	m_pTimer->Enabled = true;
	m_pThread->Start();

	return ShowModal();
}
//---------------------------------------------------------------------------

int __fastcall TProgressForm::User_CheckPayment( int iOperation, int nIdCount,
												UINT aIdStyle[], int aStyleCost[],
												int* pCost , int* pBalance )
{
	m_nParam1 = nIdCount;
	m_pParam1 = aIdStyle;
	m_pParam2 = aStyleCost;
	m_pIntParam2 = pCost;
	m_pIntParam1 = pBalance;
	m_nParam2 = iOperation;
	m_iOperation = OPERATION_USER_CHECKPAYMENT;
	m_DialogPanel->Caption = L"正在鉴权";
	m_pTimer->Enabled = true;
	m_pThread->Start();

	return ShowModal();
}
//---------------------------------------------------------------------------

int __fastcall TProgressForm::User_ConfirmPayment( int iOperation, int nIdCount,
													UINT aIdStyle[], int* pBalance )
{
	m_nParam1 = nIdCount;
	m_pParam1 = aIdStyle;
	m_pIntParam1 = pBalance;
	m_nParam2 = iOperation;
	m_iOperation = OPERATION_USER_CONFIRMPAYMENT;
	m_DialogPanel->Caption = L"正在支付";
	m_pTimer->Enabled = true;
	m_pThread->Start();

	return ShowModal();
}
//---------------------------------------------------------------------------

int __fastcall TProgressForm::User_SubmitQuestin( LPCSTR strQuestion )
{
	//wcscpy( m_strParam, strQuestion );
	strcpy( m_strBuff, strQuestion );
	m_iOperation = OPERATION_USER_SUBMITQA;
	m_DialogPanel->Caption = L"正在提交";
	m_pTimer->Enabled = true;
	m_pThread->Start();

	return ShowModal();
}
//---------------------------------------------------------------------------

int __fastcall TProgressForm::User_StyleScore( UINT idStyle, int iType, int* pScrUser, int* pScrAverage )
{
	//add laq
	m_iOperation = OPERATION_USER_SUBMITSCORE;

	if( *pScrUser<0 )
		m_DialogPanel->Caption = L"正在获取评分";
	else
		m_DialogPanel->Caption = L"正在提交评分";

	m_nParam1 = idStyle;
	m_nParam2 = iType;
	m_pIntParam1 = pScrUser;
	m_pIntParam2 = pScrAverage;

	m_pTimer->Enabled = true;
	m_pThread->Start();

	return ShowModal();
}
//---------------------------------------------------------------------------
int __fastcall TProgressForm::User_UploadSong( LPCTSTR strFileName, TSHAREINFO* pShareInfo )
{
	m_iOperation = OPERATION_USER_UPLOADSONG;

	if( pShareInfo ){
		wcscpy( m_strParam1, strFileName );
		m_DialogPanel->Caption = L"正在上传";
		m_pParam1 = (void*)pShareInfo;
	}
	else{
		m_DialogPanel->Caption = L"正在验证上传许可";
		m_pTimer->Enabled = true;
	}

	m_pThread->Start();

	return ShowModal();
}
//---------------------------------------------------------------------------

int __fastcall TProgressForm::User_StyleUpload( int iType, int nDataSize, char* pData )
{
	m_iOperation = OPERATION_USER_UPLOADSTYLE;

	m_DialogPanel->Caption = L"正在上传";
	m_pParam1 = (void*)pData;
	m_nParam1 = nDataSize;
	m_nParam2 = iType;

	m_pThread->Start();

	return ShowModal();
}
//---------------------------------------------------------------------------

void __fastcall TProgressForm::Operation()
{
	switch( m_iOperation ){
		case OPERATION_MM_SAVEMEDIA:
			if( m_iSaveState==STATE_IDLE ){
				m_iSaveState = STATE_SAVING;

				if( m_nParam1==FILETYPE_MIDI ){
					if( m_nParam2 & SAVE_COMPOSE ){
						BYTE *pData = new BYTE[2000000];
						int nSize = 2000000, ret = 0,
							iTrack = m_nParam2 & 0xFF;

						if( iTrack==0 )
							ret = GetComposeData( g_lstOpusStages, g_iMelodyKey, nSize, pData, true );
						else
							ret = GetMidiTrackData( nSize, pData, iTrack-1, -1, -1, NULL, NULL );

						if( ret==0 ){
							f_MM_SaveMidi( NULL, pData, nSize, -1, ((AnsiString)m_strParam1).c_str(), m_nParam1 );
							PostMessage( Handle, MSG_OPERATE_COMPLETE, 0, 0 );
						}
						else {
							DebugPrint("Compose error.\n");
							PostMessage( Handle, MSG_OPERATE_FAILED, -1, 0 );
						}

						delete[] pData;
					}
					else{ //FILETYPE_TRANSMID = 0
						f_MM_Save( Handle, m_nParam2, ((AnsiString)m_strParam1).c_str(), g_iMelodyKey << 8 );
					}
				}
				else{
					int iTrack = m_nParam2 & 0xFF;

					if( (m_nParam2 & SAVE_COMPOSE) && iTrack>0 ){
						BYTE *pData = new BYTE[2000000];
						int nSize = 2000000, ret = 0;

						ret = GetMidiTrackData( nSize, pData, iTrack-1, -1, -1, NULL, NULL );
						if( ret==0 ){
							int iBank = g_aMidiTracks[iTrack-1]->bank;
							f_MM_SaveMidi( Handle, pData, nSize, iBank, ((AnsiString)m_strParam1).c_str(), m_nParam1 );
						}
						else {
							DebugPrint("Get midi data error.\n");
							PostMessage( Handle, MSG_OPERATE_FAILED, -1, 0 );
						}

						delete[] pData;
					}
					else{
						bool bMuted = false;

						if( iTrack==0 )
							SetTrackParams( false );
						else if( IsTrackMute(ST_AUDIO, iTrack-1) ){
							bMuted = true;
							f_MM_SetAudioTrackParam( iTrack-1, 0,
											(float)(g_aAudioTracks[iTrack-1]->volume / 100.0) );
						}

						f_MM_Save( Handle, m_nParam2, ((AnsiString)m_strParam1).c_str(), m_nParam1 );

						if( iTrack==0 )
							SetTrackParams( true );
						else if( bMuted ){
							f_MM_SetAudioTrackParam( iTrack-1, 0, 0 );
						}
					}
				}
			}
			else if( m_iSaveState & STATE_CONFIRMING ){
				int nBalance;
				m_iConfirmResult = f_CS_ConfirmPayment( g_infoUser.accountInfo.ID, m_nParam4,
													m_nParam3, (UINT*)m_pParam1, &nBalance );

				if( SOFTWARE_ID!=e_Pro_Lite && ( m_iConfirmResult==e_VerifyInsufficient
												|| m_iConfirmResult==0 ))
					g_infoUser.accountInfo.balance = nBalance;

				PostMessage( Handle, MSG_PAYMENTCONFIRMED, -1, 0 );
			}
			break;

		case OPERATION_MM_LOAD:
			if( m_nParam1==FILETYPE_MIDI ){
				m_iOperationResult = f_MM_LoadMidiMelody( Handle, ((AnsiString)m_strParam1).c_str() );
			}
			else{
				m_iOperationResult = f_MM_LoadAudio(Handle, ((AnsiString)m_strParam1).c_str(),
											m_nParam1 - 1, g_iMelodyTimeSignature, g_nMelodyTempo);
			}

			if( m_iOperationResult!=S_OK ){
				PostMessage( Handle, MSG_OPERATE_FAILED, m_iOperationResult, 0 );
			}
			else
				PostMessage( Handle, MSG_OPERATE_COMPLETE, 0, 0 );

			break;

		case OPERATION_MM_FXAPPLY:
			m_iOperationResult = f_MM_AudioFxProcess( g_iSelAudio, m_dblParam1, m_dblParam2, Handle );

			if( m_iOperationResult!=S_OK )
				PostMessage( Handle, MSG_OPERATE_FAILED, m_iOperationResult, 0 );
			else
				PostMessage( Handle, MSG_OPERATE_COMPLETE, 0, 0 );

			break;

		case OPERATION_PROJ_SAVE:
			if( SaveProject( ((AnsiString)m_strParam1).c_str(), PROJ_MODE_NORMAL, Handle )==TRUE ){
			}
			else{
			}

			break;

		case OPERATION_PROJ_LOAD:
			if( LoadProject( ((AnsiString)m_strParam1).c_str(), Handle )==TRUE ){
			}
			else{
			}
			break;

		case OPERATION_USER_LOGIN:
			m_iOperationResult = f_CS_Login( &g_infoUser, true );
			PostMessage( Handle, MSG_OPERATE_COMPLETE, m_iOperationResult, 0 );
			break;

		case OPERATION_USER_REGISTER:
			m_iOperationResult = f_CS_Register( &g_infoUser, m_nParam1 );
			if( m_iOperationResult==0 ){
				PostMessage( Application->MainForm->Handle, MSG_NETWORKMESSAGE,
						MAKELONG( 0, e_loginResponse ), (LPARAM)&g_infoUser );
			}

			PostMessage( Handle, MSG_OPERATE_COMPLETE, m_iOperationResult, 0 );
			break;

		case OPERATION_USER_CHECKPAYMENT:
			m_iOperationResult = f_CS_CheckPayment( g_infoUser.accountInfo.ID, m_nParam2,
													m_nParam1, (UINT*)m_pParam1, (int*)m_pParam2,
													m_pIntParam2, m_pIntParam1 );
			PostMessage( Handle, MSG_OPERATE_COMPLETE, m_iOperationResult, 0 );
			break;

		case OPERATION_USER_CONFIRMPAYMENT:
			m_iOperationResult = f_CS_ConfirmPayment( g_infoUser.accountInfo.ID, m_nParam2,
													m_nParam1, (UINT*)m_pParam1, m_pIntParam1 );
			PostMessage( Handle, MSG_OPERATE_COMPLETE, m_iOperationResult, 0 );
			break;

		case OPERATION_USER_SUBMITQA:

			m_iOperationResult = f_CS_SubmitQnA( g_infoUser.accountInfo.ID, m_strBuff );
			PostMessage( Handle, MSG_OPERATE_COMPLETE, m_iOperationResult, 0 );
			break;

		case OPERATION_USER_SUBMITSCORE:
			m_iOperationResult = f_CS_StyleScore( g_infoUser.accountInfo.ID,
													m_nParam1, m_nParam2,
													m_pIntParam1, m_pIntParam2 );
			PostMessage( Handle, MSG_OPERATE_COMPLETE, m_iOperationResult, 0 );
			break;

		case OPERATION_USER_UPLOADSONG:
		{
			TSONGINFO infoSong;
			if( m_pParam1 ){

//				memcpy( &infoSong, &g_infoSong, sizeof(TSONGINFO) );

				string strTmp = GBToUTF8(g_infoSong.strSongName);
				strcpy( infoSong.strSongName, strTmp.c_str() );

				strTmp = GBToUTF8(g_infoSong.strSinger);
				strcpy( infoSong.strSinger, strTmp.c_str() );

				strTmp = GBToUTF8(g_infoSong.strOriginal);
				strcpy( infoSong.strOriginal, strTmp.c_str() );

				strTmp = GBToUTF8(g_infoSong.strArranger);
				strcpy( infoSong.strArranger, strTmp.c_str() );

				strTmp = GBToUTF8(g_infoSong.strLyricist);
				strcpy( infoSong.strLyricist, strTmp.c_str() );

				strTmp = GBToUTF8(g_infoSong.strComposer);
				strcpy( infoSong.strComposer, strTmp.c_str() );

				strTmp = GBToUTF8(g_infoSong.strDescription);
				strcpy( infoSong.strDescription, strTmp.c_str() );

				memcpy( infoSong.iMusicStyle, g_infoSong.iMusicStyle, sizeof(char)*4 );
				memcpy( infoSong.aStyleIDs, g_infoSong.aStyleIDs, sizeof(UINT)*32 );
				infoSong.iCreation   = g_infoSong.iCreation;
				infoSong.iSubmit     = g_infoSong.iSubmit;
				infoSong.size        = g_infoSong.size;
				infoSong.iTempo      = g_infoSong.iTempo;
				infoSong.iTS         = g_infoSong.iTS;
				infoSong.iSingerType = g_infoSong.iSingerType;
				infoSong.cpjPrice    = g_infoSong.cpjPrice;
				infoSong.cpjVersion  = g_infoSong.cpjVersion;

				int lenght;
				if( g_infoSong.strIconName ){
					lenght = strlen(g_infoSong.strIconName);
					infoSong.strIconName = new char[lenght+1];
					strcpy( infoSong.strIconName, g_infoSong.strIconName );
					infoSong.strIconName[lenght] = '\0';
				}

				if( g_infoSong.strLyric ){
					strTmp = GBToUTF8(g_infoSong.strLyric);
					lenght = strlen(strTmp.c_str());
					infoSong.strLyric = new char[lenght+1];
					strcpy( infoSong.strLyric, strTmp.c_str() );
					infoSong.strLyric[lenght] = '\0';
				}

				if( g_infoSong.strCpjName ){
					lenght = strlen(g_infoSong.strCpjName);
					infoSong.strCpjName = new char[lenght+1];
					strcpy( infoSong.strCpjName, g_infoSong.strCpjName );
					infoSong.strCpjName[lenght] = '\0';
				}

				infoSong.strMp3Name = new char[((AnsiString)m_strParam1).Length()+1];
				strcpy( infoSong.strMp3Name, ((AnsiString)m_strParam1).c_str() );
			}

			m_iOperationResult = f_CS_UploadSong( g_infoUser.accountInfo.ID,
										m_pParam1 ? &infoSong : NULL,
										Handle,
										(TSHAREINFO*)m_pParam1 );
			PostMessage( Handle, MSG_OPERATE_COMPLETE, m_iOperationResult, 0 );


//			SAFE_DELETE(infoSong.strIconName)
//			SAFE_DELETE(infoSong.strLyric)
//			SAFE_DELETE(infoSong.strMp3Name)
			
			break;
		}
		case OPERATION_USER_UPLOADSTYLE:
			m_iOperationResult = f_CS_UploadStyle( m_nParam2, g_infoUser.accountInfo.ID,
													m_nParam1, (char*)m_pParam1, Handle );
			PostMessage( Handle, MSG_OPERATE_COMPLETE, m_iOperationResult, 0 );
			break;

		default:
			PostMessage( Handle, MSG_OPERATE_FAILED, -1, 0 );
			break;
	}
}
//---------------------------------------------------------------------------

void __fastcall TProgressForm::OnCanceled(TObject *Sender)
{
	if( m_iOperation>0 ){
		m_iOperationResult = e_UserCanceled;
		Canceled();
	}
}
//---------------------------------------------------------------------------

void TProgressForm::Canceled()
{
	DebugPrint( "Canceled.\n" );

	if( m_iOperation==OPERATION_MM_SAVEMEDIA ){
		if( m_iSaveState & STATE_SAVING ){
			f_MM_UserCanceled();
			m_pThread->WaitFor();
		}
		if( m_iSaveState & STATE_CONFIRMING ){
			m_pTimer->Enabled = false;
			f_CS_CancelOperation();
			m_pConfirmThread->WaitFor();
		}

		if( m_iFileHandle>0 ){
			FileClose( m_iFileHandle );
			m_iFileHandle = 0;
		}

		if( FileExists( m_strParam1 ) )
			DeleteFile( m_strParam1 );
	}
	else{
		if( m_iOperation==OPERATION_MM_LOAD || m_iOperation==OPERATION_MM_SAVE ){
			f_MM_UserCanceled();
		}
		else if( m_iOperation==OPERATION_USER_LOGIN
						|| m_iOperation==OPERATION_USER_REGISTER
						|| m_iOperation==OPERATION_USER_CHECKPAYMENT
						|| m_iOperation==OPERATION_USER_CONFIRMPAYMENT
						|| m_iOperation==OPERATION_USER_SUBMITQA
						|| m_iOperation==OPERATION_USER_UPLOADSONG ){
			m_pTimer->Enabled = false;
			f_CS_CancelOperation();
		}

		m_pThread->WaitFor();
	}

	m_iOperation = 0;
	ModalResult = mrCancel;
	DebugPrint( "exit progress.\n" );
}
//---------------------------------------------------------------------------

void __fastcall TProgressForm::TimerProc(TObject* Sender)
{
	if( m_pTimer->Interval==200 ){
		m_nPos += 20;

		if( m_nPos>=m_nMaxPos ){
			m_nPos -= m_nMaxPos;
		}

		m_pbProgress->Invalidate();
	}
	else{
		m_iOperationResult = e_WaitTimeout;
		Canceled();
	}
}
//---------------------------------------------------------------------------

void __fastcall TProgressForm::FormKeyDown(TObject *Sender, WORD &Key, TShiftState Shift)
{
	switch( Key ){
	case VK_ESCAPE:
		Canceled();
		break;
	}
}
//---------------------------------------------------------------------------

void __fastcall TProgressForm::FormClose(TObject *Sender, TCloseAction &Action)
{
	if( m_iFileHandle>0 ){
		FileClose( m_iFileHandle );
		m_iFileHandle = 0;
	}
}
//---------------------------------------------------------------------------

