/* -*- c-file-style: "ruby"; indent-tabs-mode: nil -*- */

/*
 *  Copyright (C) 2006 Eriko Sato
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2, or (at your option)
 *  any later version.
 *
 *  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 copyED 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-1307, USA.
 */

#include <stdio.h>
#include <glib/gi18n.h>
#include "kz-rb-ext.h"

#define INIT_PRE_RB "kazehakase-init-pre"
#define INIT_RB "kazehakase-init"

extern VALUE rb_load_path;
void Init_stack _((VALUE *));

static VALUE mKz;

static VALUE
rb_kz_gettext(VALUE self, VALUE msgid)
{
    return CSTR2RVAL(_(RVAL2CSTR(msgid)));
}

static void
Init_kz (void)
{
    gchar *config_dir, *actions_dir;

    mKz = rb_define_module("Kz");

    config_dir = g_build_filename(g_get_home_dir(), "."PACKAGE, NULL);
    actions_dir = g_build_filename(config_dir, "actions", NULL);
    rb_define_const(mKz, "CONFIG_DIR", rb_str_new2(config_dir));
    rb_define_const(mKz, "ACTIONS_DIR", rb_str_new2(actions_dir));
    g_free(config_dir);
    g_free(actions_dir);

    rb_define_module_function(mKz, "gettext", rb_kz_gettext, 1);
}

void
kz_ext_init (KzWindow *kz)
{
    VALUE cKzWindow;
    VALUE stack_start;
    gchar *dirname;
    char *argv[] = {"kazehakase"};

    ruby_init();
    Init_stack(&stack_start);

    ruby_init_loadpath();

    ruby_script("kazehakase");
    ruby_set_argv(1, argv);

    dirname = g_build_filename(KZ_DATADIR, "ext", "ruby", NULL);
    rb_ary_unshift(rb_load_path, rb_str_new2(dirname));
    g_free(dirname);

    rb_ary_unshift(rb_load_path, rb_str_new2(KZ_RUBY_EXTDIR));

    Init_kz();

    rb_funcall(Qnil, rb_intern("require"), 1, rb_str_new2(INIT_PRE_RB));

    if (RTEST(rb_const_get(mKz, rb_intern("ENABLE")))) {
        Init_kz_rb_window(mKz);
        Init_kz_rb_embed(mKz);
        Init_kz_rb_embed_event(mKz);
        Init_kz_rb_conf(mKz);
        Init_kz_rb_downloader(mKz);
        Init_kz_rb_downloader_group(mKz);

        cKzWindow = rb_const_get(mKz, rb_intern("Window"));
        rb_funcall(cKzWindow, rb_intern("set_default"), 1, GOBJ2RVAL(kz));

        rb_funcall(Qnil, rb_intern("require"), 1, rb_str_new2(INIT_RB));
    }
}

void
kz_ext_close (gboolean success)
{
    rb_funcall(mKz, rb_intern("close"), 0);
    ruby_cleanup(0);
}
