/**************************************************************************\
 ibtk (Insomnia's Basic ToolKit)

  By Insomnia (Steaphan Greene)
  (insomnia@core.binghamton.edu)

  Copyright (C) 1999 Steaphan Greene

  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.

\**************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "iwindow.h"
#include "ilistbox.h"
#include "ibutton.h"
#include "ibox.h"
#include "itextbox.h"
#include "idialogs.h"

IWindow *__fopen_window__;
IButton * __fopen_ok_button__;
int __fopen_stat__ = 0;

void __fopen_sel__(IDoDad *p, IDoDad *d, int x);
void __fopen_desel__(IDoDad *p, IDoDad *d, int x);
void __fopen_ok__(IDoDad *p, IDoDad *d, int x);
void __fopen_cancel__(IDoDad *p, IDoDad *d, int x);

FILE *ifopendialog(char *types, char *mode, char *caption)  {
  char *list[256];
  char buf[256];
  char tn[L_tmpnam];
  tmpnam(tn);
  sprintf(buf, "/bin/ls -1aF %s > %s%c", types, tn, 0);
  system(buf);

  FILE *fs = fopen(tn, "r");
  int nfls = 0;
  char *nm;
  nm = fgets(buf, 256, fs);
  while(nm != NULL)  {
    if(nm[strlen(nm)-1] == '\n') nm[strlen(nm)-1] = 0;
    list[nfls] = new char[strlen(nm)+1];
    sprintf(list[nfls], "%s%c", nm, 0);
    ++nfls;
    nm = fgets(buf, 256, fs);
    }
  fclose(fs);

  IWindow w(200, 400);
  w.SetTitle(caption);
  getcwd(buf, 256);
  ITextBox dir(buf, &w, 0, 0, 200, 20);
  IListBox l(list, nfls, &w, 0, 20, 200, 360);
  IButton O("Open", &w, 0, 380, 100, 20);
  IButton C("Cancel", &w, 100, 380, 100, 20);
  __fopen_window__ = &w;
  __fopen_ok_button__ = &O;
  O.Disable();
  O.SetClickCallback(&__fopen_ok__);
  C.SetClickCallback(&__fopen_cancel__);
  l.SetDCCallback(&__fopen_ok__);
  l.SetSelCallback(&__fopen_sel__);
  w.DispatchEvents();
  if((!__fopen_stat__) || l.NumSelections() < 1) return NULL;
  sprintf(buf, "%s%c", l.GetSelection(0), 0);
  nm = buf;
//  printf("Opening \"%s\"\n", nm);
  if(nm[strlen(nm)-1] == '@' || nm[strlen(nm)-1] == '*')
    nm[strlen(nm)-1] = 0;
  return(fopen(nm, mode));
  }

void __fopen_ok__(IDoDad *p, IDoDad *d, int x)  {
  __fopen_stat__ = 1;
  __fopen_window__->Close();
  }

void __fopen_cancel__(IDoDad *p, IDoDad *d, int x)  {
  __fopen_stat__ = 0;
  __fopen_window__->Close();
  }

void __fopen_sel__(IDoDad *p, IDoDad *d, int x)  {
  __fopen_ok_button__->Enable();
  }

void __fopen_desel__(IDoDad *p, IDoDad *d, int x)  {
  __fopen_ok_button__->Disable();
  }
