#include "viewerSDL.h"
#include "Func.h"
#include "TaskManager.h"
#include "viewer_types.h"
#include "fb.h"

#define UGA 1

extern void post2runLoop(void *);

#define default_sdl_flag SDL_INIT_TIMER | SDL_INIT_JOYSTICK

ViewerSDL::ViewerSDL() {}
ViewerSDL::~ViewerSDL() {}

#define DEVICE_NAME "/dev/fb0"
#define DIV_BYTE 8

Uint32 *
ViewerSDL::video_init(TaskManager *manager, int bpp, int width, int height)
{

#if defined(__linux__)
  
    int fd_framebuffer ;
    struct fb_var_screeninfo vinfo;
    struct fb_fix_screeninfo finfo;
    
    // 読み書き用にファイルを開く 
    fd_framebuffer = open( DEVICE_NAME , O_RDWR);
    if ( !fd_framebuffer ) {
      send_current_error_msg("Framebuffer device open error !");
      exit(1);
    }
    send_current_information("The framebuffer device was opened !");
	
    // 固定スクリーン情報取得 
    if ( ioctl( fd_framebuffer , FBIOGET_FSCREENINFO , &finfo ) ) {
	    send_current_error_msg("Fixed information not gotton !");
	    exit(2);
    }
    
    // 変動スクリーン情報取得 
    if ( ioctl( fd_framebuffer , FBIOGET_VSCREENINFO , &vinfo ) ) {
      send_current_error_msg("Variable information not gotton !");
      exit(3);
    }

    close(fd_framebuffer);

    width = vinfo.xres;
    height = vinfo.yres;
    bpp = vinfo.bits_per_pixel;

#endif
        
    Uint32 sdl_flag = default_sdl_flag | SDL_INIT_VIDEO;
    Uint32 *p;
	
    if (SDL_Init(sdl_flag) < 0) {
	fprintf(stderr,"Couldn't initialize SDL: %s\n", SDL_GetError());
	exit(1);
    }

    screen = SDL_SetVideoMode(width, height, bpp, SDL_HWSURFACE);
    if (screen == NULL) {
	fprintf(stderr, "Couldn't set SDL mode: %s\n", SDL_GetError());
	SDL_Quit();
	exit(1);
    }

    this->width = screen->w;
    this->height = screen->h;
    this->bpp = screen->format->BitsPerPixel;
    
    p = (Uint32*)manager->allocate(screen->pitch*height);

    return p;
}

void
ViewerSDL::clean_pixels()
{
    //bzero(pixels, sizeof(int)*width*height);
  
    //SDL_FillRect(screen,NULL,SDL_MapRGB(screen->format,0,0,0));
}

void
ViewerSDL::clear_screen()
{

#if !UGA
    SDL_BlitSurface(bitmap, NULL, screen, NULL);
    SDL_UpdateRect(screen, 0, 0, 0, 0);        
#endif

}

uint32_t *
ViewerSDL::flip_screen(uint32_t *old)
{
#if UGA

    bitmap = SDL_CreateRGBSurfaceFrom((void *)old,
				      screen->w, screen->h,
				      screen->format->BitsPerPixel,
				      screen->pitch,
				      //redMask, greenMask, blueMask, alphaMask);
				      redMask, greenMask, blueMask, 0);

    SDL_BlitSurface(bitmap,NULL,screen,NULL);
    SDL_UpdateRect(screen,0,0,0,0);

#endif

    return old;
}

void
ViewerSDL::free_device()
{
    free(bitmap->pixels);
    SDL_FreeSurface(bitmap);
}
