/*
 * This file is part of libtqtvd_astronav
 *
 * Copyright (C) 2008-2017 TQTVD Software
 * Copyright (C) 2017 Mirakulo Software (mirakulo@mirakulo.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */


#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <math.h>
#include <execinfo.h>
#include <string.h>
#include "IGraphicManagerAdapter.h"

#include "IAstroNavPlayer.h"
#include "AstroNavPlayerFactory.h"

#define ARRAY_SIZE(x)  ((int) (sizeof(x) / sizeof(x[0])))

using namespace AstroNav;

void signalCatcher(int signum)
{
	void *array[10];
	size_t size;
	char **strings;
	size_t i;

	printf("signal %d catched: abort.\n", signum);

	size = backtrace (array, 10);
	strings = backtrace_symbols (array, size);

	printf ("Obtained %zd stack frames.\n", size);

	for (i = 0; i < size; i++)
		printf ("%s\n", strings[i]);

	free (strings);

	abort();
}



class HtmlPlayerObject : public virtual IAstroNavPlayerUpdateListener 
{

private:
	
	IGraphicManagerAdapter*              m_gm;
	IGraphicManagerAdapterSurface*      m_screen;
	IGraphicManagerAdapterSurface*      m_mainScreen;
	int                    m_mainScreenX0;
	int                    m_mainScreenY0;
	IAstroNavPlayer*       m_player;
	int                    m_width;
	int                    m_height;	

public:

    HtmlPlayerObject(int width, int height, IGraphicManagerAdapter* gm, IGraphicManagerAdapterSurface* mainScreen) 
    {
		m_gm = gm;
		m_mainScreen = mainScreen;

		m_screen = m_gm->CreateSurface( width, height, 32 );
		if (m_screen == NULL)
		{
			printf("Failed creating primary surface.\n");
			return;
		}

		m_screen->Clear();

		m_screen->SetBlendMode(IGraphicManagerAdapterSurface::BLENDMODE_COMPOSE);
    }


    ~HtmlPlayerObject() 
    {
		delete m_screen;
		m_screen = NULL;
		m_gm = NULL;
    }


    void updateCb(IGraphicManagerAdapterSurface *surface, int x0, int y0, int width, int height)
    {

	    if (surface == m_screen)
	    {
			ARectangle region ( m_mainScreenX0 + x0, m_mainScreenY0 + y0, m_mainScreenX0 + x0 + width, m_mainScreenY0 + y0 + height );

			ARectangle rect ( x0, y0, width, height );

			printf("update  (x1,y1) (x2,y2) = (%d,%d) (%d,%d)\n", region.x, region.y, region.w, region.h);

			m_mainScreen->Blit( m_screen, &rect, m_mainScreenX0 + x0, m_mainScreenY0 + y0, 0xff );

			m_mainScreen->Flip( &region );
	    }

    }

	bool start(std::string url, std::string css, int x0, int y0) 
	{
		m_mainScreenX0 = x0;
		m_mainScreenY0 = y0;

		m_player = AstroNavPlayerFactory::getInstance().reservePlayer(m_gm, this);

//		m_player->setBackgroundColor(0xffffcc00);

		printf ("chamada ao play()... \n"); 
		
		if ( IAstroNavPlayer::STATE_PLAYING == m_player->play(m_screen, url, 0, 0, m_width - x0, m_height - y0, css, true))
		{
			printf ("play() ok.\n");
			return true;
		}
		else
		{
			printf ("play() falhou.\n");	
			return false;
		}
	}


	bool stop() 
	{
		if (IAstroNavPlayer::STATE_READY == m_player->stop())
		{
			printf ("chamada ao stop()... ok\n");
			AstroNavPlayerFactory::getInstance().releasePlayer(m_player);
			m_player = NULL;
			return true;
		}
		else
		{
			printf ("chamada ao stop() failed... ok\n");
			return false;
		}		
	}

};



int main(int argc, char *argv[])
{
    signal(SIGSEGV, &signalCatcher);

    int width = 800, height = 600, depth = 32;
    char* url = "http://google.com";
    char* css = "";
	HtmlPlayerObject* htmlPlayer;

    // simple arg parsing
    int argCount = 1;
    char* option;
    while (argCount < argc) {
        bool optionIsUnknown=true;
        option = argv[argCount];
        if ((strcmp(option, "--help")==0) || (strcmp(option,"-h")==0))
        {
            printf("usage:\n%s [--help] [-h] [--width w] [--height h] [--depth d] [[--css] css file] [[--url] url]\n",argv[0]);
            return 0;
        }
        else if (argv[argCount][0]!='-')
        {
            optionIsUnknown=false;
            url=argv[argCount];
        }else if (argCount+1<argc){
            if (strcmp(option, "--width") == 0){
                optionIsUnknown=false;
                width = (int)strtol(argv[++argCount], NULL, 10);
                }
            else if (strcmp(option, "--height") == 0){
                optionIsUnknown=false;
                height = (int)strtol(argv[++argCount], NULL, 10);
            }
            else if (strcmp(option, "--depth") == 0){
                optionIsUnknown=false;
                depth = (int)strtol(argv[++argCount], NULL, 10);
            }
            else if (strcmp(option, "--css") == 0){
                optionIsUnknown=false;
                css = argv[++argCount];
            }
            else if (strcmp(option, "--url") == 0){
                optionIsUnknown=false;
                url = argv[++argCount];
            }
        }

        if (optionIsUnknown)
            fprintf(stderr, "error: unknown option %s\n", argv[argCount]);

        // next arg
        argCount += 1;
    }
    printf("Using --width %d --height %d --depth %d --css %s --url %s\n", width, height, depth, css, url);

#if 0
{
        printf("\"main\"\n");
        TQTVD::GraphicManager::GraphicManagerAdapter gm = TQTVD::GraphicManager::GraphicManagerAdapter::getInstance();
        // Call Test Function
        printf("\"gm.SmokeTest();\"\n"); fflush(stdout);
        gm.SmokeTest();
        printf("concluido.");
        usleep(5*1000*1000);
        return 0;
}
#endif


#error FIX ME
	IGraphicManagerAdapter* gm ;

	IGraphicManagerAdapterSurface* mainScreen;

	mainScreen = gm->CreateSurface( width, height, 32 );

	mainScreen->Clear();
	mainScreen->Flip( NULL );

	mainScreen->SetBlendMode(IGraphicManagerAdapterSurface::BLENDMODE_COMPOSE);    



	HtmlPlayerObject* htmlPlayer1;

	htmlPlayer1 = new HtmlPlayerObject(800, 600, gm, mainScreen);

	htmlPlayer1->start(url,css,50,50); 

#if 1 
	while(1)
	{
		getchar();
	}
#endif

	htmlPlayer1->stop();

	delete htmlPlayer1;

	delete mainScreen;

	return 0;

}


