/* ui_file.c: FIle menu */

#include <stdlib.h>

#include "ui.h"
#include "uit.h"
#include "canvas.h"
#include "render.h"

static int open_file(char *fname, FILE *fp, int ispipe, Widget fsbox)
{
  if (!fp)  return 0;
  CanvasPushMode(CANVASMODE_WORKING);
  ReadScene(1, &fname);
  CanvasPullMode();
  return 1;
}

static Widget CreateLoadBox(Widget parent, char *name)
{
  return CreateFileSelectionDialog(parent, name, open_file, "r");
}

static Widget infoLabel;
void SetModelInfo(char *info)
{
  SetLabelString(infoLabel, info ? info : "No model info available");
}

static Widget CreateInfoBox(Widget parent, char *name)
{
  Widget infoBox, frame;
  infoBox = CreateDialog(parent, name);
  frame = CreateFrame(infoBox, "infoFrame", "infoTitle");
  infoLabel = CreateLabel(frame, "infoLabel");
  return infoBox;
}

static int SaveImage(char *fname, FILE *fp, int ispipe, Widget saveBox)
{
  if (!fp)
    return 1;	/* no file to save anything to, so don't save */

  /* make sure the dialog box has dissappeared before saving */
  XtUnmanageChild(saveBox);
  CheckForEvents();
  CanvasRedraw();

  CanvasPushMode(CANVASMODE_WORKING);
  SaveScreen(fp);
  CanvasPullMode();

  return 0;	/* probably succes, but we have already unmanaged the file 
		 * selection box. */
}

static Widget CreateSaveImageBox(Widget parent, char *name)
{
  return CreateFileSelectionDialog(parent, name, SaveImage, "w");  
}

static void Exit(Widget w, XtPointer client_data, XtPointer call_data)
{
  exit(0);
}

extern double get_time(void);
static void StartStopAnimationCallback(Widget w, XtPointer client_data, XtPointer call_data)
{
  renderopts.animate = 1 - renderopts.animate;
  while (renderopts.animate) {
    RenderScene();
    ProcessWaitingEvents();
  }
}

void CreateFileMenu(Widget parent)
{
  Widget fileMenu = CreateSubMenu(parent, "fileButton", "fileMenu");

  CreateCascadeDialog(fileMenu, "loadButton", CreateLoadBox, "loadBox", DEFAULT_CALLBACK, NULL);
  CreateCascadeDialog(fileMenu, "infoButton", CreateInfoBox, "infoBox", DEFAULT_CALLBACK, NULL);
  CreateSeparator(fileMenu, "fileSeparator");

  CreateCascadeDialog(fileMenu, "saveImageButton", CreateSaveImageBox, "saveImageBox", DEFAULT_CALLBACK, NULL);
  CreateSeparator(fileMenu, "fileSeparator");

  CreatePushButton(fileMenu, "startStopAnimationButton", StartStopAnimationCallback, NULL);
  CreateSeparator(fileMenu, "fileSeparator");

  CreatePushButton(fileMenu, "exitButton", Exit, NULL);
}
