/*
 * filer module
 *
 *  2000/11/13	nak@pluto.dti.ne.jp
 *
 *  Original is ....
 *		bmpviewr.c(sample src)
 *		issued: 2000/4/26
 *		author: c.mos
 *              .... thanks!
 */

#include <sys/bios.h>
#include <sys/process.h>
#include <sys/fcntl.h>
#include <string.h>
#include "std.h"

#define LCD_CHAR_CY 18
#define LIST_X 		0
#define LIST_Y 		0

static char *dirname[2] = { "/rom0",  "/ram0" };

BOOL get_entry(fent_t far *, int);
int list_file(int);

BOOL get_entry(fent_t far *fentp, int index)
{
	int i;
	int count = 0;
	int entries = fs_getil(cwfs)->_n_entries(cwfs);
	for(i=0; i < entries; i++) {
		if(fs_getil(cwfs)->_getent(cwfs, i, fentp) == E_FS_SUCCESS
			&& fentp->count != -1  && (fentp->mode & ~(FMODE_R|FMODE_W)) == 0) {
			if(count++ == index) return TRUE;
		}
	}
	return FALSE;
}

int list_file(int dir)
{
	fent_t fent;
	int x2;
	int files = 0;
	
	chdir(dirname[dir]);		/* ディレクトリ切り換え */
	text_screen_init();
	
	if( is_colorswan() ) font_set_color(CLR_STATUS_WWC);
	else font_set_color(CLR_STATUS);
	x2 = text_put_string(LIST_X, LIST_Y, dirname[dir]);
	text_fill_char(x2, 0, TEXT_SCREEN_WIDTH - x2, CHAR_SPACE);
	font_set_color(CLR_NORMAL);
	disp_status("←X→:切替 A:決定 B:戻る",TEXT_SCREEN_HEIGHT-1);
	
	while(get_entry(&fent, files)) {
		text_put_substring(LIST_X + 1, LIST_Y + files + 1, fent.name, MAXFNAME);
		if(++files >= LCD_CHAR_CY - LIST_Y - 1) break;
	}
	if(!files)
		text_put_string(0, LIST_Y+1, "No File");	/* ファイルが存在しない場合 */
	
	return files;
}

BOOL select_file(char far *path)
{
	fent_t fent;
	int dir = 0;
	int files;
	int select = 0;
	int select0;

NewDir:
	select = 0;
	files = list_file(dir);
	for(;;) {
		select0 = select;
		if(files) text_put_char(LIST_X, LIST_Y + select + 1, CHAR_MARK);	/* 選択マーク表示 */
		switch(key_wait()) {
		case KEY_A:			/* 決定 */
			if(files) {
				get_entry(&fent, select);
				strcpy(path, dirname[dir]);	/* フルパス作成 */
				strcat(path, "/");
				strcat(path, fent.name);
				text_screen_init();
				return TRUE;
			}
			break;			/* no_file で決定ボタン押された場合は入力無視 */
		case KEY_B:			/* 戻る */
			return FALSE;
		case KEY_LEFT1:		/* rom/ram 切り換え */
		case KEY_RIGHT1:
			dir ^= 1;
			goto NewDir;
		case KEY_DOWN1:
			if(files) {
				if(++select >= files) select = 0;
			}
			goto CsrUpDown;
		case KEY_UP1:
			if(files) {
				if(select-- == 0) select = files - 1;
			}
CsrUpDown:	if(select != select0)
				text_put_char(LIST_X, LIST_Y + select0 + 1, ' ');	/* 選択マーククリア */
			continue;
		}
	}
}

size_t read_file(char far *path, void *buffer)
{
	int fd;
	size_t size;
	if((fd = open(path, FMODE_R, 0)) >= 0) {
		size = read(fd, buffer, -(int)buffer);
		close(fd);
		*((BYTE*)buffer + size) = '\0';
		return size;
	} else {
		int x = text_put_string(0, 0, "Cannot Read ");
		text_put_string(x, 0, path);
		key_wait();
		return 0;
	}
}

