/* Released into the Public Domain
   Gurkan Sengun <gurkan@phys.ethz.ch> */

#include <iostream>
#include <sys/ioctl.h>
#include <termios.h>
#include <sys/poll.h>                   /* poll for keyboard input */
#include <unistd.h>
#include "MilkyPlay.h"

#define SHELL

using namespace std;

static struct termios stored_settings;

void set_keypress(void)
{
    struct termios new_settings;
    tcgetattr(0,&stored_settings);
    new_settings=stored_settings;
    new_settings.c_lflag &= (~ICANON);
    new_settings.c_lflag &= (~ECHO);
    new_settings.c_cc[VTIME] = 0;
    new_settings.c_cc[VMIN] = 1;
    tcsetattr(0,TCSANOW,&new_settings);
    return;
}

void reset_keypress(void)
{
    tcsetattr(0,TCSANOW,&stored_settings);
    return;
}

int main (int argc, const char * argv[]) 
{
	struct pollfd pollfds;
	int result, nread;
	char buffer[128];
	int timeout = 1;
	int loop=0;

	cout << "- MilkyPlay -" << endl << endl;

	/* Initialize pollfds; we're looking at input, stdin */
	pollfds.fd = 0;             /* stdin */
	pollfds.events = POLLIN;    /* Wait for input */

	XModule* pModule = new XModule();

#ifdef SHELL

	if (argc != 2)
	{
		cout << "Say: milkyplay <filename>" << endl;

		return 0;
	}

	cout << "Playing " << argv[1] << " (press ctrl+c to quit) ..." << endl;

	pModule->loadModule(argv[1]);
#else

	pModule->loadModule("/Users/peterbar//Desktop/work/crimson lotus.it");

#endif

	char str[MP_MAXTEXT+1];
	pModule->getTitle(str, false);

	cout << "Title: " << str << endl;

	PlayerGeneric* pPlayer = new PlayerGeneric(44100);
	// CoreAudio wants small buffer sizes
	pPlayer->setBufferSize(4096);
	// Select high quality mixer
	pPlayer->setResamplerType(MixerSettings::MIXER_LERPING_RAMPING);
	// Sample data is shifted twice (/4) => less sample data overflows
	pPlayer->setSampleShift(1);
	// 256 is default (= 100%)
	pPlayer->setPanningSeparation(256);

	pPlayer->startPlaying(pModule, false, 0);

	set_keypress();
	while (!pPlayer->hasSongHalted())
	{
		cerr << pPlayer->getOrder() << "/" << pPlayer->getRow() << "  \r";
		usleep(50000);
		result = poll(&pollfds, 1, timeout);
		switch (result) {
		    default:
		        if (pollfds.revents && POLLIN) {
			    nread = read(0, buffer, 1);
			    if (nread != 0) {
				buffer[nread] = 0;
				if (buffer[0]=='q') exit(0);
				if (buffer[0]=='l') pPlayer->setRepeat(pPlayer->isRepeating() ^ 1);
				if (buffer[0]=='p') if (!pPlayer->isPaused()) pPlayer->pausePlaying(); else pPlayer->resumePlaying();
			    }
			}
		}
	}
	reset_keypress();
	
	mp_sint32 pos;
	pos = pPlayer->getLastUnvisitedPosition();
	cerr << pos << endl;
	
	pPlayer->stopPlaying();
	
	/*mp_sint32 res = pPlayer->exportToWAV("/test.wav", pModule);
	if (res >=0)
	{
		mp_sint32 time = res / 44100;
		printf("%i:%i",time/60,time%60);
	}*/
	
	delete pPlayer;
	
	delete pModule;
	
	cout << "Player stopped..." << endl;
		
	return 0;
}
