#include "viewerPS3.h"
#include "fb.h"
#include "types.h"
#include "ps3fb/cp_vt.h"
#include "ps3fb/cp_fb.h"
#include <stdio.h>

#define default_sdl_flag SDL_INIT_TIMER | SDL_INIT_JOYSTICK

ViewerPS3::ViewerPS3() {}
ViewerPS3::~ViewerPS3() {}

#if defined(__linux__)

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

ScreenInfo 
ViewerPS3::get_fbdev_addr()
{
    ScreenInfo info;

    cp_vt_open_graphics(&vt);
    cp_fb_open(&fb);

    info.xres = fb.w;
    info.yres = fb.h; 
    info.vbpp = 32;
    info.fbptr[0] = (uint32_t *)fb.draw_addr[ 0 ];
    info.fbptr[1] = (uint32_t *)fb.draw_addr[ 1 ];

    return info;
}

#else /* !defined(__linux__) */
ScreenInfo 
ViewerPS3::get_fbdev_addr(void) { 
    ScreenInfo tmp = {0,0,0,0};
    return tmp;
}
#endif /* defined(__linux__) */


Uint32 *
ViewerPS3::video_init(TaskManager *manager, int bpp, int width, int height)
{
    // Uint32 sdl_flag = default_sdl_flag |  SDL_INIT_VIDEO;
    Uint32 sdl_flag = default_sdl_flag ;

    if (SDL_Init(sdl_flag) < 0) {
	fprintf(stderr,"Couldn't initialize SDL: %s\n",SDL_GetError());
	exit(1);
    }

    screen_info = get_fbdev_addr();

    uint32_t *pixels =  screen_info.fbptr[frame_ndx];

    if (pixels == 0) {
	fprintf(stderr, "Cannot get frame buffer!\n");
    	pixels = (new Uint32[width*height*32/8]);
    }
    this->width = screen_info.xres;
    this->height = screen_info.yres;
    this->bpp = screen_info.vbpp;

    return pixels;
}

void
ViewerPS3::clean_pixels()
{
}

void
ViewerPS3::clear_screen()
{
}

uint32_t *
ViewerPS3::flip_screen(uint32_t *old)
{
        // At the vsync, the previous frame is finished sending to the CRT
        // cp_fb_wait_vsync( &fb );

        // Send the frame just drawn to the CRT by the next vblank
#ifdef __linux__
        cp_fb_flip( &fb, frame_ndx );
#endif

        frame_ndx  = frame_ndx ^ 0x01;
	return (uint32_t*)fb.draw_addr[ frame_ndx ];
}


void
ViewerPS3::free_device()
{
#ifdef __linux__
    cp_vt_close(&vt);
    cp_fb_close(&fb);
#endif
}

/* end */
