// Description:
//   Controller
//
// Copyright (C) 2003 Frank Becker
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation;  either version 2 of the License,  or (at your option) any  later
// version.
//
// This program 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 General Public License for more details
//
#include "SDL.h"

#include <Trace.hpp>
#include <Point.hpp>

#include "BlockModel.hpp"
#include "BlockController.hpp"

const Point3Di px( 1, 0, 0);
const Point3Di mx(-1, 0, 0);
const Point3Di py( 0, 1, 0);
const Point3Di my( 0,-1, 0);
const Point3Di pz( 0, 0, 1);
const Point3Di mz( 0, 0,-1);

BlockController::BlockController( BlockModel &model, BlockViewBase &view):
    _model(model),
    _view(view),
    _eventWatcher(0),
    _eventInjector(0)
{ 
}

BlockController::~BlockController()
{
    delete _eventWatcher;
    delete _eventInjector;
}

bool BlockController::hasEvent( SDL_Event &event)
{
    if( SDL_PollEvent( &event))
    {
	return true;
    }
    if( _eventInjector)
    {
	return _eventInjector->getEvent( event);
    }

    return false;
}

bool BlockController::update( void)
{
    SDL_Event event;
    while( hasEvent( event))
    {
	if( _eventWatcher) _eventWatcher->notify(event);

	switch( event.type )
	{
	    case SDL_KEYDOWN:
//	    	LOG_INFO << "Key is " << event.key.keysym.sym << "\n";
		switch( event.key.keysym.sym)
		{
		    case SDLK_BACKQUOTE:
		    case SDLK_ESCAPE:
			return false;
			break;

		    case SDLK_LEFT:
			_model.moveBlock( eLeft);
			break;
		    case SDLK_RIGHT:
			_model.moveBlock( eRight);
			break;
		    case SDLK_UP:
			_model.moveBlock( eUp);
			break;
		    case SDLK_DOWN:
			_model.moveBlock( eDown);
			break;
		    case SDLK_SPACE:
			_model.moveBlock( eIn);
			break;

		    case SDLK_q:
			_model.rotateBlock( px, mz, py, px);
			break;
		    case SDLK_a:
			_model.rotateBlock( px, pz, my, mx);
			break;
		    case SDLK_w:
			_model.rotateBlock( pz, py, mx, py);
			break;
		    case SDLK_s:
			_model.rotateBlock( mz, py, px, my);
			break;
		    case SDLK_e:
			_model.rotateBlock( my, px, pz, pz);
			break;
		    case SDLK_d:
			_model.rotateBlock( py, mx, pz, mz);
			break;

		    case SDLK_F12:
			_view.snapshot();
			break;

		    default:
			break;
		}
		break;

	    case SDL_QUIT:
		LOG_INFO << "Quit!\n";
		return false;
		break;

	    default:
		break;
	}
    }
    return true;
}
