#include "sapview.h"
#include "constants.h"
#include <fstream.h>
#include "sapLib.h"


SapView::SapView(BRect rect)
	: BView(rect, "SapView", B_FOLLOW_ALL_SIDES, B_NAVIGABLE | B_WILL_DRAW)
	{
		BRect r(10, 20, 40, 40);
		button = new BButton(r, "aa", "+", new BMessage('SONG'));
		AddChild(button);
		
		r.top +=25;
		button1 = new BButton(r, "bb", "-", new BMessage('KONG'));
		AddChild(button1);
		
		r.left = button->Bounds().right+20;
		r.top = button->Bounds().top;
		r.right+= 120;
		
		
		textc = new BStringView(r, "textv", "", B_WILL_DRAW | B_NAVIGABLE);
		AddChild(textc);
		saplayer = NULL;
	}





void SapView::AttachedToWindow(void)
{
	button->SetTarget(this);
	button1->SetTarget(this);
	BView::AttachedToWindow();
	fOpenPanel = new BFilePanel(B_OPEN_PANEL, new BMessenger(this), NULL, B_FILE_NODE, false);

}
void SapView::MessageReceived(BMessage *message)
{
	switch(message->what)
	{
	case MENU_FILE_OPEN:
		fOpenPanel->Show();
	break;
	
	case B_SIMPLE_DATA:
		if (message->FindRef("refs", &ref) == B_NO_ERROR) StartP();
	break;
	
	case B_REFS_RECEIVED:
		if (message->FindRef("refs", &ref) == B_NO_ERROR) StartP();
	break;
	
	case 'SONG':
		sapPlaySong(i++);
	break;
	default:
	case 'KONG':
		sapPlaySong(i--);
	break;
	BView::MessageReceived(message);
	break;
	}
}

void SapView::StartP(void)
{

	int songNum = 0;
	char AmountSongs[256];
	
	media_raw_audio_format format;
	
	BEntry entry(&ref,true);
	entry.GetPath(&path);
	
	char *file2play = strdup(path.Path());
	sapMUSICstrc *fish=sapLoadMusicFile(file2play);
	
	if(fish->defSong== -1) fish->defSong=1;
	
	if(fish->numOfSongs== -1) fish->numOfSongs=1;
	if(songNum!=0)
		sapPlaySong(songNum);
	else
		songNum=fish->defSong;
		
		i = fish->numOfSongs;
		
	if(saplayer) {
	saplayer->Stop();
	delete saplayer;

	}
	
	sprintf(AmountSongs, "Amount of songs: %d", (int)fish->numOfSongs);
	textc->SetText(AmountSongs);
	
	format.frame_rate = 44100;
    format.channel_count = 2;
    
	format.format = media_raw_audio_format::B_AUDIO_SHORT;
	format.byte_order = B_MEDIA_LITTLE_ENDIAN;
	
    format.buffer_size = 1024;
    
    cout << format.buffer_size << endl;
 
 	saplayer = new BSoundPlayer(&format, "SapPlayer", BufferProc, NULL, NULL);
 
 	if(saplayer->InitCheck() != B_OK) {
 		saplayer->Stop();
 		delete saplayer;
 	saplayer = NULL;
 	}
 	  
 
 	saplayer->Start();
 	
	printf("Initialized Audio: %f hz %s\n", format.frame_rate, (format.channel_count == 1 ? "Mono" : "Stereo"));
 	saplayer->SetHasData(true);
}

void SapView::BufferProc(void *the_cookie, void *buffer, size_t size, const media_raw_audio_format &format)
{
	sapRenderBuffer((signed short *)buffer, size/4);
}

SapView::~SapView()
{
	if(saplayer) {
	saplayer->Stop();
	delete saplayer;
	}
}