#include <k/cli.h>
#include <k/io.h>
#include <k/str.h>

typedef struct buffer {
	char* cur;
	kiochan channel;
	sz run;
	char buf [];
} buffer;

static buffer*
buffer_new(void* mem, kiochan channel, sz run) {
	buffer* r = mem;
	r -> cur = r -> buf;
	r -> channel = channel;
	r -> run = run;
	return r;
}

static kiocond
buffer_flush(buffer* b) {
	ksraw str = {b -> cur - b -> buf, b -> buf};
	b -> cur = b -> buf;
	return kiosend(b -> channel, str, null);
}

static kcond
buffer_send(buffer* b, const char* str) {
	ksmut buf = { b->run - (b->cur - b->buf), b->cur };
	ksraw src = { 0, str };
	kscond sc = kscp(src, buf, &src.size);
	if (sc != kscond_ok) return sc;

	b->cur += src.size;
	if (b->cur >= (b->buf + b->run)) {
		return buffer_flush(b);
	} else return kiocond_ok;
}

kcond
kcli_usage(kcli_set prg, kiochan ch) {
	ubyte buf_space [sizeof(buffer) + 256];
	buffer* out = buffer_new(buf_space, ch, 256);

	const char* msg [] = {
		prg.name, " v", prg.version, "\n\n",
		prg.desc, "\n\n",
	};
	for (sz i = 0; i != sizeof msg / sizeof msg[0]; ++ i) {
		kcond c = buffer_send(out, msg[i]);
		if (!kokay(c)) return c;
	}
	
	return buffer_flush(out);
}
