/*
  ==============================================================================

    This file was auto-generated!

  ==============================================================================
*/

#include "NiallsSocketLib/UDPSocket.h"
#include "MainComponent.h"
#include "GameListPanel.h"
#include "PatcherPanel.h"

//------------------------------------------------------------------------------
MainContentComponent::MainContentComponent()
{
    String ipAddress;
    UDPSocket tempSock;

    discoverGames();

    addAndMakeVisible(mainTabs = new TabbedComponent(TabbedButtonBar::TabsAtTop));
    mainTabs->setTabBarDepth (30);
    mainTabs->addTab ("Launcher", Colour (0xffeeece1), new GameListPanel(*this), true);
    mainTabs->addTab ("Patcher", Colour (0xffeeece1), new PatcherPanel(*this), true);
    mainTabs->setCurrentTabIndex (0);

    ipAddress << "IP Address: " << tempSock.getIpAddress().c_str();
    addAndMakeVisible (ipAddressLabel = new Label ("ipAddressLabel", ipAddress));
    ipAddressLabel->setJustificationType(Justification(Justification::centredRight));
    ipAddressLabel->setFont (Font (15.00f, Font::plain));
    ipAddressLabel->setEditable (false, false, false);
    ipAddressLabel->setColour (TextEditor::textColourId, Colours::black);
    ipAddressLabel->setColour (TextEditor::backgroundColourId, Colour (0x00000000));

    setSize (600, 400);
}

//------------------------------------------------------------------------------
MainContentComponent::~MainContentComponent()
{
    mainTabs = nullptr;
    ipAddressLabel = nullptr;
}

//------------------------------------------------------------------------------
void MainContentComponent::paint (Graphics& g)
{
    g.fillAll (Colour (0xFFEEECE1));
}

//------------------------------------------------------------------------------
void MainContentComponent::resized()
{
    mainTabs->setBounds(8, 8, getWidth()-16, getHeight()-16);
    ipAddressLabel->setBounds(getWidth()-8-256, 6, 256, 24);
}

//------------------------------------------------------------------------------
void MainContentComponent::addGameToPatcher(const String& gameName,
										    const String& listenPort,
										    const String& sendAddress,
										    const String& sendPort)
{
	PatcherPanel *panel(dynamic_cast<PatcherPanel *>(mainTabs->getTabContentComponent(1)));

	if(panel)
	{
		panel->addGame(gameName, listenPort, sendAddress, sendPort);
	}
}

//------------------------------------------------------------------------------
void MainContentComponent::addListenPort(int port)
{
	int i;

	//First check we don't already have this port active.
	for(i=0;i<oscThreads.size();++i)
	{
		if(port == oscThreads[i]->getListenPort())
		{
			AlertWindow::showMessageBoxAsync(AlertWindow::WarningIcon,
											 "Cannot create port",
											 "This port is already in use.");

			return;
		}
	}

	//If we get here, the port was available and we can create the thread.
	oscThreads.add(new OSCThread(port));
}

//------------------------------------------------------------------------------
void MainContentComponent::setListenPort(int index, int port)
{
	if(index < oscThreads.size())
		oscThreads[index]->setListenPort(port);
}

//------------------------------------------------------------------------------
void MainContentComponent::addSendDestination(int index,
											  const String& address,
											  int port)
{
	if(index < oscThreads.size())
		oscThreads[index]->addSendDestination(address, port);
}

//------------------------------------------------------------------------------
void MainContentComponent::removeSendDestination(int threadIndex,
												 const String& address,
												 int port)
{
	if(threadIndex < oscThreads.size())
		oscThreads[threadIndex]->removeSendDestination(address, port);
}

//------------------------------------------------------------------------------
void MainContentComponent::setSendPort(int threadIndex, int destIndex, int port)
{
	if(threadIndex < oscThreads.size())
		oscThreads[threadIndex]->setSendPort(destIndex, port);
}

//------------------------------------------------------------------------------
void MainContentComponent::setSendAddress(int threadIndex,
										  int destIndex,
										  const String& address)
{
	if(threadIndex < oscThreads.size())
		oscThreads[threadIndex]->setSendAddres(destIndex, address);
}

//------------------------------------------------------------------------------
void MainContentComponent::discoverGames()
{
    File rootDir(File::getSpecialLocation(File::currentApplicationFile).getParentDirectory());
    DirectoryIterator it(rootDir, false, "*", File::findDirectories);

    while(it.next())
    {
        Array<File> possibleExecutables;
        const File& gameDir(it.getFile());
        File metadata(gameDir.getChildFile("metadata.txt"));
        File screenshot(gameDir.getChildFile("screenshot.png"));
#ifdef WIN32
        gameDir.findChildFiles(possibleExecutables,
                               File::findFiles,
                               false,
                               "*.exe");
#elif defined(OSX)
        gameDir.findChildFiles(possibleExecutables,
                               File::findDirectories,
                               false,
                               "*.app");
#endif

        if(metadata.exists() &&
           screenshot.exists() &&
           (possibleExecutables.size() > 0))
        {
            String tempstr;
            GameDetails *game = new GameDetails();
            String metadataString(metadata.loadFileAsString());

            game->name = metadataString.substring(0, metadataString.indexOfChar('\n')).removeCharacters("\r");
            tempstr = metadataString.substring(metadataString.indexOfChar('\n')+1);
            game->authors = tempstr.substring(0, tempstr.indexOfChar('\n')).removeCharacters("\r");
            game->description = tempstr.substring(tempstr.indexOfChar('\n')+1).removeCharacters("\r");

            game->screenshot = ImageFileFormat::loadFrom(screenshot);

            game->executable = possibleExecutables[0];

            games.add(game);
        }
		else if (possibleExecutables.size() > 0)
		{
			String tempstr;
			GameDetails *game = new GameDetails();

			game->name = possibleExecutables[0].getFileNameWithoutExtension();
			game->authors = "???";
			game->description = "???";
			game->screenshot = Image();
			game->executable = possibleExecutables[0];

            games.add(game);

			tempstr << "Could not find metadata.txt/screenshot.png for " << possibleExecutables[0].getFileName();
			AlertWindow::showMessageBoxAsync(AlertWindow::WarningIcon,
											 "Error loading metadata",
											 tempstr);
		}
    }
}
