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

#include "kz-rb-ext.h"

#define _SELF(obj) RVAL2DLGRP(obj)
#define DLGRP (kz_downloader_group_get_instance())

static VALUE
rb_kz_dlgrp_initialize(VALUE self)
{
    RBGTK_INITIALIZE(self, kz_downloader_group_new());
    return Qnil;
}

static VALUE
rb_kz_dlgrp_instance(VALUE self)
{
    return GOBJ2RVAL(DLGRP);
}

static VALUE
rb_kz_dlgrp_items(VALUE self)
{
    return GSLIST2ARY(_SELF(self)->items);
}

static VALUE
rb_kz_dlgrp_s_items(VALUE self)
{
    return GSLIST2ARY(DLGRP->items);
}

static VALUE
rb_kz_dlgrp_add(int argc, VALUE *argv, VALUE self)
{
    VALUE uri_or_dl, filename;

    rb_scan_args(argc, argv, "11", &uri_or_dl, &filename);

    if (!RTEST(rb_obj_is_kind_of(uri_or_dl, rb_cString))) {
        kz_downloader_group_add_downloader(DLGRP, RVAL2DL(uri_or_dl));
    } else if (NIL_P(filename)) {
        kz_downloader_group_add_item(DLGRP, RVAL2CSTR(uri_or_dl));
    } else {
        kz_downloader_group_add_item_with_filename(DLGRP,
                                                   RVAL2CSTR(uri_or_dl),
                                                   RVAL2CSTR(filename));
    }

    return Qnil;
}

static VALUE
rb_kz_dlgrp_remove(VALUE self, VALUE downloader)
{
    kz_downloader_group_remove_item(DLGRP, RVAL2DL(downloader));
    return Qnil;
}

void
Init_kz_rb_downloader_group(VALUE mKz)
{
    VALUE cKzDownloaderGroup;

    cKzDownloaderGroup = G_DEF_CLASS(KZ_TYPE_DOWNLOADER_GROUP,
                                     "DownloaderGroup", mKz);

    rb_define_singleton_method(cKzDownloaderGroup, "instance",
                               rb_kz_dlgrp_instance, 0);
    rb_define_singleton_method(cKzDownloaderGroup, "items",
                               rb_kz_dlgrp_s_items, 0);
    rb_define_singleton_method(cKzDownloaderGroup, "add",
                               rb_kz_dlgrp_add, -1);
    rb_define_singleton_method(cKzDownloaderGroup, "remove",
                               rb_kz_dlgrp_remove, 0);

    rb_define_method(cKzDownloaderGroup, "initialize",
                     rb_kz_dlgrp_initialize, 0);
    rb_define_method(cKzDownloaderGroup, "items",
                     rb_kz_dlgrp_items, 0);

    G_DEF_SETTERS(cKzDownloaderGroup);
}
