/*****************************************************************************
 * JVLC.java: JNI interface for vlc Java Bindings
 *****************************************************************************
 * Copyright (C) 1998-2005 the VideoLAN team
 *
 * Authors: Filippo Carone <filippo@carone.org>
 *
 * 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/

/* These are a must*/
#include <jni.h>
#include <vlc/vlc.h>
#include <jawt.h>
#include <jawt_md.h>

#include <X11/Xlib.h> // for Xlibs graphics functions

/* JVLC internal imports, generated by gcjh */
#include "org_videolan_jvlc_JVLCCanvas.h"

/*
 * This will only work on X11 at the moment
 */

JNIEXPORT void JNICALL Java_org_videolan_jvlc_JVLCCanvas_paint (JNIEnv *env, jobject canvas, jobject graphics) {

  JAWT awt;
  JAWT_DrawingSurface* ds;
  JAWT_DrawingSurfaceInfo* dsi;
  JAWT_X11DrawingSurfaceInfo* dsi_x11;
  jboolean result;
  jint lock;
  GC gc;
    
  vlc_value_t value;
  short i;

  /* Get the AWT */
  awt.version = JAWT_VERSION_1_3;
  if (JAWT_GetAWT(env, &awt) == JNI_FALSE) {
    printf("AWT Not found\n");
    return;
  }

  /* Get the drawing surface */
  ds = awt.GetDrawingSurface(env, canvas);
  if (ds == NULL) {
    printf("NULL drawing surface\n");
    return;
  }

  /* Lock the drawing surface */
  lock = ds->Lock(ds);
  if((lock & JAWT_LOCK_ERROR) != 0) {
    printf("Error locking surface\n");
    awt.FreeDrawingSurface(ds);
    return;
  }

  /* Get the drawing surface info */
  dsi = ds->GetDrawingSurfaceInfo(ds);
  if (dsi == NULL) {
    printf("Error getting surface info\n");
    ds->Unlock(ds);
    awt.FreeDrawingSurface(ds);
    return;
  }

  /* Get the platform-specific drawing info */
  dsi_x11 = (JAWT_X11DrawingSurfaceInfo*)dsi->platformInfo;


  /* Now paint */
  gc = XCreateGC(dsi_x11->display, dsi_x11->drawable, 0, 0);
  XSetBackground(dsi_x11->display, gc, 0);

  value.i_int = dsi_x11->drawable;
  VLC_VariableSet( 0, "drawable", value );

  XFreeGC(dsi_x11->display, gc);

  /* Free the drawing surface info */
  ds->FreeDrawingSurfaceInfo(dsi);

  /* Unlock the drawing surface */
  ds->Unlock(ds);

  /* Free the drawing surface */
  awt.FreeDrawingSurface(ds);
}
