#include "WindowManager.h"

static void TransWindow(WindowRef w, Boolean vis)
{
  WindowTransitionAction Action;
  if(vis)
    Action = kWindowShowTransitionAction;
  else
    Action = kWindowHideTransitionAction;
  TransitionWindow(w, kWindowZoomTransitionEffect, Action, NULL);
}

static void InitWindowContext(VWindow * w)
{
  GLint Attribs[] = {AGL_RGBA, AGL_DOUBLEBUFFER, AGL_DEPTH_SIZE, 32, AGL_NONE};
  AGLPixelFormat Format;
  
  Format = aglChoosePixelFormat(NULL, 0, Attribs);
  w->TheContext = aglCreateContext(Format ,NULL);
  aglSetCurrentContext(w->TheContext);
  /* I don't know if this is actually necessary or not... */
  /* I think so -- just forgot it */
  aglSetDrawable(w->TheContext, GetWindowPort(w->TheWindow));
  aglDestroyPixelFormat(Format);
  
  glLineWidth(1.0);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_BLEND);  glEnable(GL_ALPHA_TEST);  glAlphaFunc(GL_GREATER, 0.0f);  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); /* Wireframe mode */
  glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 100.0);
}

static pascal OSStatus WindowWasClosed(EventHandlerCallRef nextEvent, EventRef theEvent, void * userData) {
  #pragma unused(nextEvent, theEvent)
  VWindow * w;
  
  w = (VWindow *) userData;
  if (w->quitOnClose) QuitApplicationEventLoop();
  return eventNotHandledErr;
}

void InitWindow(VWindow * w)
{
  GDHandle mainDevice;
  Point screenSize;
  Rect Bounds;
  EventTypeSpec eventType;
  
  mainDevice = GetMainDevice();
  screenSize.h = (**mainDevice).gdRect.right;
  screenSize.v = (**mainDevice).gdRect.bottom;
  
  /* This will center the window onscreen. */
  SetRect(&Bounds, ((screenSize.h / 2) - 200), ((screenSize.v / 2) - 200),
    ((screenSize.h / 2) + 200), ((screenSize.v / 2) + 200));
  CreateNewWindow(kDocumentWindowClass, 
    kWindowCloseBoxAttribute + kWindowCollapseBoxAttribute, 
    &Bounds, &w->TheWindow);
  SetWindowTitleWithCFString(w->TheWindow, CFSTR("Vectorized"));
  InstallStandardEventHandler(GetWindowEventTarget(w->TheWindow));
  
  eventType.eventClass = kEventClassWindow;
  eventType.eventKind = kEventWindowClosed;
  InstallWindowEventHandler(w->TheWindow, NewEventHandlerUPP(WindowWasClosed), 1, &eventType, w, NULL);
  
  TransWindow(w->TheWindow, true);
  
  InitWindowContext(w);
  
  w->quitOnClose = 0;
}

void CleanUpWindow(VWindow * w)
{
  TransWindow(w->TheWindow, false);
  aglDestroyContext(w->TheContext);
  DisposeWindow(w->TheWindow);
  w->TheWindow = NULL;
}
