#include "reseauSDL.h"

ReseauSDL::ReseauSDL ()
	{
	//font=SFont_InitFont(IMG_Load(FONT_PATH));	
	couche1=0;
	couche2=0;
	couche3=0;
	width=800;
	height=600;
	R=NULL;
	active=0;
	}
	
void ReseauSDL::showScreen(int x=800, int y=600)
	{
	if( SDL_Init(SDL_INIT_VIDEO) < 0 ) 
		{
		fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError());
		return ;
		}
	atexit(SDL_Quit);
	screen = SDL_SetVideoMode(800,600, 32, SDL_HWSURFACE);
	if( screen==NULL ) 
		{
		fprintf(stderr, "Could not create surface: %s\n", SDL_GetError());
		return ;
		}
	active=1;
	}

void ReseauSDL::hideScreen()
	{
	SDL_FreeSurface(screen);
	}

void ReseauSDL::setReseau(Reseau *r)
	{
	R=r;
	couche1=r->Icouche.getNumber();
	couche2=r->Hcouche.getNumber();
	couche3=r->Ocouche.getNumber();
	}
void ReseauSDL::drawNeuron(int couche, int neur)
	{
	SDL_Rect r;
	char red;
	char green;
	double syn;
	r.x= 100 + (300*(couche-1));
	if(couche==1)
		{
		r.y= (600*(neur+1)) / (couche1+1) ;
		for(int i=0;i<couche2;i++)
			{
			red=0;
			green=0;
			syn=R->Icouche.getSynapse(neur,i).getWeight();
			//cout << "DA - " << syn ;
			if(syn<0.0)
				{
				if(syn<-2.0) syn=-2.0;
				syn=syn*-1.0;
				syn*=128.0;
				red=(char)syn;
				}
			else if(syn>0.0)
				{
				if(syn>2.0) syn=2.0;
				syn*=128.0;
				green=(char)syn;
				}
			//cout << " r=" << (int)red << " g=" << (int)green << endl;
			DrawLine(screen, r.x , r.y , 100+(300*couche) , (600*(i+1))/(couche2+1) , red,green,0);
			}
		}
	if(couche==2)
		{
		r.y=(600*(neur+1))/(couche2+1);
		for(int i=0;i<couche3;i++)
			{
			red=0;
			green=0;
			syn=R->Hcouche.getSynapse(neur,i).getWeight();
			if(syn<0.0)
				{
				if(syn<-2.0) syn=-2.0;
				syn=syn*-1.0;
				syn*=128.0;
				red=(char)syn;
				}
			else if(syn>0.0)
				{
				if(syn>2.0) syn=2.0;
				syn*=128.0;
				green=(char)syn;
				}
			//cout << " r=" << (int)red << " g=" << (int)green << endl;
			DrawLine(screen, r.x , r.y , 100+(300*couche) , (600*(i+1))/(couche3+1) , red,green,0);
			}
		}
	if(couche==3)
		{
		r.y=  ((600*(neur+1))/(couche3+1));
		}
	r.x-=2;
	r.y-=2;
	r.w=5;
	r.h=5;
	SDL_FillRect(screen,&r, SDL_MapRGB(screen->format, 0,0,255));
	}

bool ReseauSDL::getState()
	{
	return active;
	}
void ReseauSDL::setState(bool st)
	{
	if(st==active) return;
	if(st==true)
		{
		showScreen();
		active=st;
		}
	else
		{
		hideScreen();
		active=st;
		SDL_Quit();
		}
	}	
void ReseauSDL::refresh()
	{
	if(active)
		{
		SDL_Rect r;
		r.x=0;
		r.y=0;
		r.w=800;
		r.h=600;
		SDL_FillRect(screen,&r, SDL_MapRGB(screen->format, 255,255,255));
		for(int i=0;i<couche1;i++) drawNeuron(1,i);
		for(int i=0;i<couche2;i++) drawNeuron(2,i);
		for(int i=0;i<couche3;i++) drawNeuron(3,i);
		SDL_Flip (screen);
		}
	}
	/*
void ReseauSDL::redraw_synapses(Reseau &R)
	{
	refresh();
	}
	*/
