/*
  sdl - SDL Demo for Cairographics

  Copyright (C) 2004 Eric Windisch
*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

/*
#include <SDL.h>
#include <cairo.h>
*/
#include <SDL/SDL.h>
#include <cairo/cairo.h>

unsigned char* image;

SDL_Surface* create_cairo_image(int width, int height)
{
  int bpp = 32; /* bits per pixel */
  int btpp = 4; /* bytes per pixel */
  int stride = width * btpp;
  
  image = calloc(stride * height, 1);
  
  cairo_surface_t* cairo_surface;
  cairo_surface = cairo_image_surface_create_for_data(image, CAIRO_FORMAT_ARGB32, width, height, stride);
  cairo_t* cr = cairo_create(cairo_surface);
  
  cairo_set_source_rgb(cr, 1, 1, 1);
  cairo_move_to(cr, 0, 0);
  cairo_line_to(cr, width, height);
  cairo_stroke(cr);
  
  cairo_surface_destroy(cairo_surface);
  cairo_destroy (cr);
  
  Uint32 rmask, gmask, bmask, amask;
  
  rmask = 0x00ff0000;
  gmask = 0x0000ff00;
  bmask = 0x000000ff;
  amask = 0xff000000;
  
  SDL_Surface* sdl_surface = SDL_CreateRGBSurfaceFrom((void*)image, width, height, bpp, stride, rmask, gmask, bmask, amask);
  
  return sdl_surface;
}

SDL_Surface* init_SDL(int width, int height, int bpp)
{
  SDL_Surface* screen;

  if (SDL_Init(SDL_INIT_VIDEO) < 0)
  {
    fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
    exit(1);
  }
  
  screen = SDL_SetVideoMode(width, height, bpp, SDL_SWSURFACE);

  if (screen == NULL)
  {
    fprintf(stderr, "Unable to set %ix%i video: %s\n", width, height, SDL_GetError());
    exit(1);
  }

  SDL_WM_SetCaption("Cairo SDL DEMO", "DEMO");
  
  return screen;
}

int main(int argc, char** argv)
{
  SDL_Surface* screen;
  SDL_Surface* cairo_image;
  SDL_Event event;
  int width = 12 * 36;
  int height = 10 * 36;
  int loop = 1;
  
  screen = init_SDL(width, height, 16);
  
  SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 255, 0, 255));
  
  cairo_image = create_cairo_image(width, height);
  
  SDL_BlitSurface(cairo_image, NULL, screen, NULL);
  SDL_UpdateRect(screen, 0, 0, 0, 0);

  while (loop)
  {
    while (SDL_PollEvent (&event))
    {
      switch (event.type)
      {
      case SDL_KEYDOWN:
        if (event.key.keysym.sym == SDLK_ESCAPE)
        {
          loop = 0;
        }
        /*
        else if (event.key.keysym.sym == SDLK_f)
        {
          SDL_WM_ToggleFullScreen(screen);
        }
        */
        break;

      case SDL_QUIT:
        loop = 0;
        break;
      }
    }
  }

  SDL_FreeSurface(cairo_image);
  SDL_FreeSurface(screen);
  
  free(image);
  
  return 0;
}
