// This is a Demo of the Irrlicht Engine (c) 2005-2009 by N.Gebhardt.
// This file is not documented.

#include "CMainMenu.h"


// Define some values that we'll use to identify individual GUI controls.
enum
{
    GUI_ID_QUIT_BUTTON = 3,
    GUI_ID_CONTINUE_BUTTON = 2,
    GUI_ID_NEW_BUTTON = 1,
    GUI_ID_FILE_OPEN_BUTTON=4,
    GUI_ID_WINDOW_MAP=5,
    GUI_ID_BUTTON_OK_MAP=6,
    GUI_ID_SETTINGS_BUTTON=7,
    GUI_ID_ENREG_SETTINGS_BUTTON=8,
    GUI_ID_ANNULE_SETTINGS_BUTTON=9,
    GUI_ID_SETTINGS_WINDOW=10
};

CMainMenu::CMainMenu()
: startButton(0), MenuDevice(0), selected(2), start(false), fullscreen(true),
	music(true), shadows(false), additive(false), transparent(true), vsync(false), aa(false)
{
    contexte=new CGameContext();
}

CMainMenu::~CMainMenu()
{
    delete startButton;
    startButton=0;
    delete continueButton;
    continueButton=0;
    delete quitButton;
    quitButton=0;
    delete window;
    window=0;
    delete combobox;
    combobox=0;
    delete buttonOK;
    buttonOK=0;

    delete MenuDevice;
    MenuDevice=0;
    delete lightMapNode;
    lightMapNode=0;
    delete dynamicNode;
    dynamicNode=0;
    delete contexte;
    contexte=0;
}



bool CMainMenu::run(bool& outFullscreen, bool& outMusic, bool& outShadows,
			bool& outAdditive, bool& outVSync, bool& outAA,
			video::E_DRIVER_TYPE& outDriver)
{
	//video::E_DRIVER_TYPE driverType = video::EDT_DIRECT3D9;
	video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
	//video::E_DRIVER_TYPE driverType = video::EDT_BURNINGSVIDEO;
	//video::E_DRIVER_TYPE driverType = video::EDT_SOFTWARE;

	MenuDevice = createDevice(driverType,
		core::dimension2d<u32>(800, 600), 16, false, false, false, this);

	/*if (MenuDevice->getFileSystem()->existFile("irrlicht.dat"))
		MenuDevice->getFileSystem()->addFileArchive("irrlicht.dat");
	else
		MenuDevice->getFileSystem()->addFileArchive("media/irrlicht.dat");*/

	video::IVideoDriver* driver = MenuDevice->getVideoDriver();
	scene::ISceneManager* smgr = MenuDevice->getSceneManager();
	gui::IGUIEnvironment* guienv = MenuDevice->getGUIEnvironment();

	core::stringw str = "My 3d Ski Resort";
	str += MenuDevice->getVersion();
	MenuDevice->setWindowCaption(str.c_str());

	// set new Skin
	gui::IGUISkin* newskin = guienv->createSkin(gui::EGST_BURNING_SKIN);
	guienv->setSkin(newskin);
	newskin->drop();

	// load font
	gui::IGUIFont* font = guienv->getFont("media/fonthaettenschweiler.bmp");
	if (font)
		guienv->getSkin()->setFont(font);

    const core::stringw filename=L"settings.xml";
    settings = new CSettingManager(filename,MenuDevice);

    //Charge les preferences graphiques
    if ( !settings->Load() )
    {
         MenuDevice->getGUIEnvironment()->addMessageBox(L"Erreur de chargement parametres",L"Le fichier settings.xml des parametres est introuvable a la racine du jeu","",true);
         fullscreen=0;
         resolutionStr=L"1280x960";
    }
    else
    {
        //récupère le paramètre fullscreen
        fullscreen=settings->getSettingAsBoolean(L"fullscreen");
        resolutionStr=settings->getSetting(L"resolution");
        printf("-get fullscreen %i\n",fullscreen);
        printf("-get resolution %s\n",settings->getSetting(L"resolution").c_str());
        printf("-get resolution2 %s\n",resolutionStr.c_str());
    }


	// add button

	startButton = guienv->addButton(core::rect<int>(80,178,250,207), 0, GUI_ID_NEW_BUTTON, L"Commencer");
    continueButton = guienv->addButton(core::rect<int>(80,236,250,265), 0, GUI_ID_CONTINUE_BUTTON, L"Continuer");
    settingsButton = guienv->addButton(core::rect<int>(80,295,250,324), 0, GUI_ID_SETTINGS_BUTTON, L"Options");
    quitButton = guienv->addButton(core::rect<int>(80,355,250,394), 0, GUI_ID_QUIT_BUTTON, L"Quitter");


	// set ambient light
	smgr->setAmbientLight( video::SColorf(0.8f, 0.8f, 0.8f) );



	// create a fixed camera
	smgr->addCameraSceneNode(0, core::vector3df(45,0,0), core::vector3df(0,0,10));


	// irrlicht logo and background
	// add irrlicht logo
	bool oldMipMapState = driver->getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);
	driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);

	/*guienv->addImage(driver->getTexture("media/irrlichtlogo3.png"),
		core::position2d<s32>(5,5));*/

	video::ITexture* irrlichtBack = driver->getTexture("media/title.jpg");

	driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, oldMipMapState);

	// query original skin color
	getOriginalSkinColor();

	// set transparency
	//setTransparency();


	// draw all

	while(MenuDevice->run())
	{
		if (MenuDevice->isWindowActive())
		{
			driver->beginScene(false, true, video::SColor(0,0,0,0));

			if (irrlichtBack)
				driver->draw2DImage(irrlichtBack,
						core::position2d<int>(0,0));

			smgr->drawAll();
			guienv->drawAll();
			driver->endScene();
		}
	}

	MenuDevice->drop();

	outFullscreen = fullscreen;
	outMusic = music;
	outShadows = shadows;
	outAdditive = additive;
	outVSync = vsync;
	outAA = aa;
    outDriver = video::EDT_OPENGL;

	return start;
}


bool CMainMenu::OnEvent(const SEvent& event)
{

	if (event.EventType == EET_GUI_EVENT)
	{
		s32 id = event.GUIEvent.Caller->getID();
		switch(id)
		{

		case GUI_ID_NEW_BUTTON: //Commencer
			if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
				//printf("New button clicked \n");

                window = MenuDevice->getGUIEnvironment()->addWindow(core::rect<s32>(100,100,400,250),true,L"Choisir une Map",0,GUI_ID_WINDOW_MAP);
                combobox = MenuDevice->getGUIEnvironment()->addComboBox(core::rect<s32>(50, 50, 250, 70),window);
                buttonOK = MenuDevice->getGUIEnvironment()->addButton(core::rect<s32>(100, 90, 200, 130),window,GUI_ID_BUTTON_OK_MAP,L"Ok");

                core::array<core::stringc> features=contexte->LoadMaps();
                combobox->clear();
                //for (std::vector<std::string>::iterator it=features.begin();it!=features.end();++it){
                for(unsigned int i = 0; i < features.size(); i++) {
                    //std::string str = *it;
                    //combobox->addItem(str);
                    core::stringw textCB(features[i]);
                    combobox->addItem(textCB.c_str());
                    //printf("add item =%s \n",features[i].c_str());
                }
				//MenuDevice->closeDevice();
				//start = true;
			}
			break;
		case GUI_ID_CONTINUE_BUTTON: //Continuer
			if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
				//printf("Continue button clicked\n");
				gui::IGUIEnvironment* guienv = MenuDevice->getGUIEnvironment();
				guienv->addFileOpenDialog(L"Choisir une partie",true,0,-1,true);
			}
			break;
		case GUI_ID_QUIT_BUTTON: //Quitter
			if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
				//printf("Quit button clicked");
				MenuDevice->closeDevice();
				start = false;
			}
			break;
        case GUI_ID_SETTINGS_BUTTON:
             if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			 {
                 createSettingsDialog();
                 return true;
			 }
            break;

        case GUI_ID_ANNULE_SETTINGS_BUTTON:
             if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			 {
                windowSettings->remove();
			 }
            break;
         case GUI_ID_ENREG_SETTINGS_BUTTON:
             if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			 {
                //if there is a selection write it
                if ( ListboxResolution->getSelected() != -1)
                   settings->setSetting(L"resolution", ListboxResolution->getListItem(ListboxResolution->getSelected()));

                settings->setSetting(L"fullscreen", CheckboxFullscreen->isChecked());
                if (settings->Save())
                {
                    MenuDevice->getGUIEnvironment()->addMessageBox(L"Parametres",L"Les parametres ont ete enregistres","",true);
                }
                windowSettings->remove();
			 }
            break;
        case GUI_ID_BUTTON_OK_MAP:
            if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED )
			{
                //printf("combobox=%s \n",core::stringc(combobox->getItem(combobox->getSelected())).c_str());
                contexte->SetSelectedMap(core::stringc(combobox->getItem(combobox->getSelected())).c_str());
                MenuDevice->closeDevice();
                start = true;
			}
            break;
		}
	}

	return false;
}

void CMainMenu::createSettingsDialog() {
    //create video settings windows
    windowSettings =  MenuDevice->getGUIEnvironment()->addWindow(core::rect<s32>(280,80,680,470),true,L"Options");
    MenuDevice->getGUIEnvironment()->addStaticText (L"Parametres d'affichage", core::rect< s32 >(100,20, 300, 40), false, true, windowSettings);

    // add listbox for resolution choice
    MenuDevice->getGUIEnvironment()->addStaticText (L"Resolution", core::rect< s32 >(10,80, 200, 100), false, true, windowSettings);
    ListboxResolution =  MenuDevice->getGUIEnvironment()->addListBox(core::rect<s32>(10,110,320,200), windowSettings, 1,true);

    //add all available options to the resolution listbox
    core::map<core::stringw, core::dimension2du>::Iterator ri = settings->ResolutionOptions.getIterator();
    for(; !ri.atEnd(); ri++)
        ListboxResolution->addItem(ri->getKey().c_str());

    //set currently selected resolution
    ListboxResolution->setSelected(settings->getSetting("resolution").c_str());

    //add checkbox to toggle fullscreen, initially set to loaded setting
    CheckboxFullscreen = MenuDevice->getGUIEnvironment()->addCheckBox(
            settings->getSettingAsBoolean("fullscreen"),
            core::rect<s32>(10,220,290,240), windowSettings, GUI_ID_SETTINGS_WINDOW,
            L"Plein ecran");

    if(fullscreen) {
        CheckboxFullscreen->setChecked(1);
    } else {
         CheckboxFullscreen->setChecked(0);
    }



    //last but not least add save button
    ButtonSave = MenuDevice->getGUIEnvironment()->addButton(
            core::rect<s32>(20,250,190,270), windowSettings, GUI_ID_ENREG_SETTINGS_BUTTON,
            L"Enregistrer les parametres");

    //exit/cancel button
    ButtonExit = MenuDevice->getGUIEnvironment()->addButton(
            core::rect<s32>(210,250,380,270), windowSettings, GUI_ID_ANNULE_SETTINGS_BUTTON,
            L"Annuler et sortir");
}

core::stringw CMainMenu::GetSelectedMap() {
    return contexte->GetSelectedMap();
}

void CMainMenu::getOriginalSkinColor()
{
	irr::gui::IGUISkin * skin = MenuDevice->getGUIEnvironment()->getSkin();
	for (s32 i=0; i<gui::EGDC_COUNT ; ++i)
	{
		SkinColor[i] = skin->getColor( (gui::EGUI_DEFAULT_COLOR)i );
	}

}


void CMainMenu::setTransparency()
{
	irr::gui::IGUISkin * skin = MenuDevice->getGUIEnvironment()->getSkin();

	for (u32 i=0; i<gui::EGDC_COUNT ; ++i)
	{
		video::SColor col = SkinColor[i];

		if (false == transparent)
			col.setAlpha(255);

		skin->setColor((gui::EGUI_DEFAULT_COLOR)i, col);
	}
}

