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

#include <vcl.h>
#pragma hdrstop

#include "ImportSegmentFormUnit.h"
#include "MessageFormUnit.h"

#define E_WrongMIDIFormat	0x00000001 //MIDI版本错误
#define E_FileFormatError	0x00000002 //语法格式错误
#define E_TSConflict		0x00000004 //节拍匹配错误
#define E_TempoConfilict	0x00000008 //速度匹配错误
#define E_LessBarsNum		0x00000010 //小节数不足
#define E_MoreBarsNum		0x00000020 //小节数过多
#define E_EmptySegment		0x00000040 //片段无有效音轨数据

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "ComboBoxComponent"
#pragma link "GeneralDialogPanel"
#pragma link "LineEdit"
#pragma link "TextButton"
#pragma resource "*.dfm"
TImportSegmentForm *ImportSegmentForm;
//---------------------------------------------------------------------------
__fastcall TImportSegmentForm::TImportSegmentForm(TComponent* Owner, TPreStylePanel* pStylePanel)
	: TForm(Owner)
{
	m_pStylePanel = pStylePanel;

	SetSegType();

	SetTransparent( this );
}
//---------------------------------------------------------------------------

void TImportSegmentForm::SetSegType()
{
	int iOldIndex = m_cbSegType->DefItemIndex;

	m_cbSegType->Clear();
	m_aParams.clear();

	TStyleItem* pStyItem = m_pStylePanel->GetStyleItem();
	DWORD dwParam = 0;
	if( pStyItem->nSegNum[0]<8 ){
		m_cbSegType->AddItem( "伴奏" );
		m_aParams.push_back( MAKELONG(pStyItem->nSegNum[0], SEGTYPE_VAR) );
	}
	if( pStyItem->nSegNum[1]<8 ){
		m_cbSegType->AddItem( "加花" );
		m_aParams.push_back( MAKELONG(pStyItem->nSegNum[1], SEGTYPE_FILL) );
	}

	int count = m_pStylePanel->GetIECount( 0, 0 );
	if( count < 4 ){
		m_cbSegType->AddItem( "前奏(大调)" );
		m_aParams.push_back( MAKELONG(count, SEGTYPE_INTRO) );
	}
	count = m_pStylePanel->GetIECount( 0, 1 );
	if( count < 4 ){
		m_cbSegType->AddItem( "前奏(小调)" );
		m_aParams.push_back( MAKELONG(count+4, SEGTYPE_INTRO) );
	}
	count = m_pStylePanel->GetIECount( 1, 0 );
	if( count < 4 ){
		m_cbSegType->AddItem( "尾奏(大调)" );
		m_aParams.push_back( MAKELONG(count, SEGTYPE_ENDING) );
	}
	count = m_pStylePanel->GetIECount( 1, 1 );
	if( count < 4 ){
		m_cbSegType->AddItem( "尾奏(小调)" );
		m_aParams.push_back( MAKELONG(count+4, SEGTYPE_ENDING) );
	}

	count = m_cbSegType->ItemsCount;
	if( count>0 ){
		if( iOldIndex<0 || iOldIndex>=count )
			m_cbSegType->DefItemIndex = 0;
		else
			m_cbSegType->DefItemIndex = iOldIndex;
	}
}
//---------------------------------------------------------------------------

void __fastcall TImportSegmentForm::OkClick(TObject *Sender)
{
	String strTips[] = {L"提示：请选择导入的MIDI文件和片段类型",
						L"提示：风格所含片段数已达上限",
						L"错误：所选文件不是标准MIDI(1)格式",
						L"错误：MIDI语法解析错误",
						L"错误：MIDI节拍不一致",
						L"错误：MIDI速度不一致",
						L"错误：伴奏片段不得少于2小节",
						L"错误：加花片段不得超过1小节",
						L"错误：片段不得超过16小节",
						L"错误：片段缺少有效音轨数据" };
	int iTip = 0;

	if( m_editFileName->Text.Length()==0 ){
		m_editFileName->SetFocus();
	}
	else{
		string strName = AnsiString(m_editFileName->Text.Trim().c_str()).c_str();
		DWORD dwParam = m_aParams[m_cbSegType->DefItemIndex];
		int segType = HIWORD( dwParam ),
			segNo = LOWORD( dwParam ),
			errCode = 0;
		char tracks[16][3];
		memset( tracks, -1, sizeof(tracks) );
		TStyleItem* pStyItem = m_pStylePanel->GetStyleItem();

		UINT idLoc = -1, idStyle = 0;
		TPROSTYLE* pStyle = pStyItem->pStyle;
		if( pStyle && pStyle->idLoc!=0 && pStyle->idLoc!=(UINT)-1 ){
			for( int i=0; i<pStyItem->aItems->Count; i++ ){
				TSegmentItem* pSeg = (TSegmentItem*)pStyItem->aItems->Items[i];
				for( int j=0; j<pSeg->aItems->Count; j++ ){
					TTrackItem* pTrk = (TTrackItem*)pSeg->aItems->Items[j];
					if( pTrk->pStyle==pStyle ){
						idLoc = pStyle->idLoc;
						idStyle = pStyle->idStyle;
						break;
					}
				}
			}
		}

		int nBars = f_CM_AddTempSegment( idLoc, idStyle, (char*)strName.c_str(), g_iMelodyTimeSignature,
											g_nMelodyTempo, segType, segNo, errCode, tracks );

		if( nBars<0 ){ //添加失败
			if( errCode & E_FileFormatError )
				iTip = 2;
			else if( errCode & E_WrongMIDIFormat )
				iTip = 3;
			else if( errCode & E_TSConflict )
				iTip = 4;
			else if( errCode & E_TempoConfilict )
				iTip = 5;
			else if( errCode & E_LessBarsNum )
				iTip = 6;
			else if( errCode & E_MoreBarsNum ){
				if( segType==SEGTYPE_FILL )
					iTip = 7;
				else
					iTip = 8;
			}
			else if( errCode & E_EmptySegment )
				iTip = 9;
		}
		else{	//添加成功
			TPROSTYLE* pTmpStyle = GetStyleInfo( -1, 0 );
			if( !pTmpStyle ){
				pTmpStyle = new TPROSTYLE;
				pTmpStyle->idLoc = -1;
				pTmpStyle->idStyle = 0;
				g_aTempStyles.push_back( pTmpStyle );
			}

			DWORD opts = OPT_DEL | OPT_VOL | (segType<SEGTYPE_INTRO ? OPT_BRUSH : 0);
			TSegmentItem* pSegItem = new TSegmentItem( pStyItem, segType, LOWORD( dwParam ),
														opts, 0, LOWORD( dwParam ), 100 );

			opts = OPT_DEL|OPT_FONTPROG|OPT_VOL | (segType<SEGTYPE_INTRO ? OPT_TEXTURE : 0);
			for( int i=0; i<16; i++ ){
				if( tracks[i][0]>=0 ){
					pSegItem->AddTrack( pTmpStyle, segNo,
										tracks[i][0],
										tracks[i][1],
										tracks[i][2],
										opts );
				}
				else
					break;
			}

			if( pStyle && pStyle->idLoc!=0 && pStyle->idLoc!=(UINT)-1 ){
				for( int i=0; i<pStyItem->aItems->Count; i++ ){
					TSegmentItem* pSeg = (TSegmentItem*)pStyItem->aItems->Items[i];
					for( int j=0; j<pSeg->aItems->Count; j++ ){
						TTrackItem* pTrk = (TTrackItem*)pSeg->aItems->Items[j];
						if( pTrk->pStyle==pStyle ){
							pTrk->pStyle = pTmpStyle;
						}
					}
				}
			}

			if( segType>=SEGTYPE_INTRO ){
				pSegItem->nBars = nBars;
			}

			g_strSegImportPath = ExtractFilePath( m_editFileName->Text ).c_str();

			m_pStylePanel->AddTempSegment( pSegItem );

			SetSegType();

			if( m_cbSegType->ItemsCount==0 ){
				iTip = 1;
				m_btnBrowse->Enabled = false;
				m_btnOk->Enabled = false;
			}
		}
	}

	m_lblTips->Font->Color = iTip<2 ? 0x00DACBBF : 0x004040FF;
	m_lblTips->Caption = strTips[iTip];
}
//---------------------------------------------------------------------------

void __fastcall TImportSegmentForm::BrowseClick(TObject *Sender)
{
	TOpenDialog * pDlg = new TOpenDialog(NULL);
	pDlg->Options << ofFileMustExist;
	pDlg->Title = L"导入";
	if( m_editFileName->Text.Length()>0 ){
		pDlg->FileName = ExtractFileName(m_editFileName->Text);
		pDlg->InitialDir = ExtractFilePath(m_editFileName->Text);
	}
	else{
        pDlg->InitialDir = g_strSegImportPath.c_str();
    }


	pDlg->Filter = "midi文件 (*.mid)|*.MID";

	if(pDlg->Execute(Handle)){
		m_editFileName->Text = pDlg->FileName;
	}

    delete pDlg;
}
//---------------------------------------------------------------------------


void __fastcall TImportSegmentForm::FormKeyDown(TObject *Sender, WORD &Key, TShiftState Shift)
{
	switch( Key ){
	case VK_RETURN:
		if(m_btnOk->Enabled)
			OkClick(NULL);
		break;

	case VK_ESCAPE:
		ModalResult = mrCancel;
		break;
	}
}
//---------------------------------------------------------------------------

void __fastcall TImportSegmentForm::FormCreate(TObject *Sender)
{
	m_panelBk->Font->Size = g_szFont9;
	m_btnBrowse->FontSize = g_szFont9;
	m_btnCancel->FontSize = g_szFont9;
	m_btnOk->FontSize = g_szFont9;
	m_cbSegType->SetFont(g_strTxtFontName, g_szFont9);
	m_editFileName->SetTextFont(g_strTxtFontName, g_szFont9);
}
//---------------------------------------------------------------------------

