#include <sde/sde.h>
#include <objgfx/objgfx30.h>

extern "C" {
  #include <sys/video.h>
  #include <vmm/paging.h>
  #include <lib/string.h>
  #include <lib/kmalloc.h>
  #include <ubixos/schedule.h>
  }

struct sdeWindows *windows = 0x0;

extern "C" void sysSDE(uInt32 cmd,void *ptr) {
  ogSurface *newBuf = 0x0;
  ogSurface *oldBuf = (ogSurface *)ptr;
  struct sdeWindows *tmp = 0x0;
  
  for (tmp=windows;tmp;tmp=tmp->next) {
    if (tmp->pid == _current->id)
      break;
    }
    
  if (tmp != 0x0) {
    while (tmp->status != windowReady)
      sched_yield();
    }
  else if (tmp == 0x0 && cmd != registerWindow) {
    kprintf("Invalid Window\n");
    return;
    }

  switch (cmd) {
    case drawWindow:
      tmp->status = drawWindow;
      break;
    case killWindow:
      tmp->status = killWindow;
      break;
    case registerWindow:
      if (oldBuf->buffer != 0x0) {
        newBuf                     = new ogSurface();
        newBuf->version            = oldBuf->version;
        newBuf->buffer             = oldBuf->buffer;
        newBuf->lineOfs            = oldBuf->lineOfs;
        newBuf->pal                = oldBuf->pal;
        newBuf->owner              = oldBuf->owner;
        newBuf->xRes               = oldBuf->xRes;
        newBuf->yRes               = oldBuf->yRes;
        newBuf->maxX               = oldBuf->maxX;
        newBuf->maxY               = oldBuf->maxY;
        newBuf->bSize              = oldBuf->bSize;
        newBuf->lSize              = oldBuf->lSize; 
        newBuf->transparentColor   = oldBuf->transparentColor;
        newBuf->dataState          = oldBuf->dataState;
        newBuf->BPP                = oldBuf->BPP;  
        newBuf->redFieldPosition   = oldBuf->redFieldPosition;
        newBuf->greenFieldPosition = oldBuf->greenFieldPosition;
        newBuf->blueFieldPosition  = oldBuf->blueFieldPosition;
        newBuf->alphaFieldPosition = oldBuf->alphaFieldPosition;
        newBuf->redShifter         = oldBuf->redShifter;
        newBuf->greenShifter       = oldBuf->greenShifter;
        newBuf->blueShifter        = oldBuf->blueShifter;
        newBuf->alphaShifter       = oldBuf->alphaShifter;
        newBuf->antiAlias          = oldBuf->antiAlias;
        tmp = (struct sdeWindows *)kmalloc(sizeof(struct sdeWindows),-2);
        tmp->buf    = newBuf;
        tmp->status = registerWindow;
        tmp->pid    = _current->id;
        tmp->prev   = 0x0;
        if (windows == 0x0) {
          windows   = tmp;
          tmp->next = 0x0;
          }
        else {
          tmp->next = windows;
          windows->prev = tmp;
          windows = tmp;
          }
        }
      else {
        kprintf("Invalid Window\n");
        }
      break;
    default:
      kprintf("Invalid SDE Command [0x%X]\n",ptr);
      break;
    }
  return;
  }