#include <gtk/gtk.h>

#include "express.h"
#include "bwindow.h"
#include "util.h"

/*gint num_bwindows;*/
app_kernel *ak;

void express_init_app_kernel()
{
  ak = (app_kernel *)pmalloc(sizeof(struct _app_kernel), "app_kernel");
#ifdef MULTIPLE_BROWSERS
  ak->num_browsers=0;
  ak->browsers=NULL;
#else
  ak->browser=NULL;
#endif
}


GtkWidget *express_new_browser()
{
  GtkWidget *newbwindow;
#ifdef MULTIPLE_BROWSERS
  browser_list *bl;
#endif

  newbwindow = bwindow_new();
  gtk_widget_show(newbwindow);

#ifdef MULTIPLE_BROWSERS
  ak->num_browsers++;
  /* insert in browser_list */
  bl = (browser_list *)pmalloc(sizeof(struct _browser_list, "browser_list"));
  bl->browser=newbwindow;
  if(ak->browsers==NULL) {
    bl->next=NULL;
  } else {
    bl->next=ak->browsers;
  }
  ak->browsers=bl;
#else
  ak->browser=newbwindow;
#endif

  return newbwindow;
}

GtkWidget *express_clone_browser(BWindow *b)
{
  GtkWidget *newbwindow;

  newbwindow = express_new_browser();

  BWINDOW(newbwindow)->history = BWINDOW(b)->history;
  if(bwindow_get_url(BWINDOW(b)))
    bwindow_set_url(BWINDOW(newbwindow), bwindow_get_url(BWINDOW(b)));

  return newbwindow;
}

void express_close_browser(BWindow *b)
{
#ifdef MULTIPLE_BROWSERS
  browser_list *bl, *pbl;

  /* remove from browser_list */
  pbl=NULL;
  for_each_browser(bl) {
    if(bl->browser == b) {
      if(pbl) pbl->next = bl->next;
      else ak->browsers = bl->next;
      free(bl);
      break;
    }
    pbl=bl;
  }
  gtk_widget_destroy(GTK_WIDGET(b));
  ak->num_browsers--;
  if(ak->num_browsers>0) {
    return(FALSE);
  } else {
    cleanexit(0);
    return(TRUE); /* :) */
  }
#else
  ak->browser=NULL;
  gtk_widget_destroy(GTK_WIDGET(b));
  cleanexit(0);
#endif
}

int cleanexit(int returncode)
{
#ifdef FORK_DOWNLOAD
  msq_rm();
#endif
  gtk_exit(returncode);

  return returncode;
}

