//  Copyright (C) 2016, mituhiromatuura all right reserved.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <kernel.h>

#include "disp.h"
#include "lcd.h"
#include "fatfs.h"
#include "index.h"
#include "wait.h"

#define INDEX_LIST_MAX 9999
static short index_list[INDEX_LIST_MAX];
static int count = 0;
extern volatile int filenum;

int index_scan(void)
{
	FRESULT res;
	DIR Dir;
	char Lfname[_MAX_LFN];
	FILINFO Finfo = {.lfname = Lfname, .lfsize = sizeof(Lfname)};

	if(0 != (disk_initialize(0) & (STA_NOINIT | STA_NODISK)))goto error;

	res = fatfs_mount(&fatfs, "", 0);
	if(FR_OK != res)goto error;

	res = fatfs_opendir(&Dir, "");
	if(FR_OK != res)goto error;

	for(count = 0; count < INDEX_LIST_MAX; count++)
	{
		index_list[count] = 0;
	}

	for(count = 0; count < INDEX_LIST_MAX; )
	{
		res = fatfs_readdir(&Dir, &Finfo);
		if(res != FR_OK)goto error;
		if('\0' == Finfo.fname[0])break;
		if(0 != Finfo.fsize)
		{
			if(NULL != strstr(Finfo.fname, ".jpg")
			|| NULL != strstr(Finfo.fname, ".JPG")
			|| NULL != strstr(Finfo.fname, ".avi")
			|| NULL != strstr(Finfo.fname, ".AVI"))
			{
				index_list[count] = atoi(Finfo.fname);
				count++;
			}
		}
	}

	int i,j,m,n,t;
	n = count;
	for(i=0;i<=n-2;i++) {
		m=i;
		for(j=i+1;j<=n-1;j++) if(index_list[j]<index_list[m]) m=j;
		t = index_list[i];
		index_list[i]=index_list[m];
		index_list[m]=t;
	}
	filenum = index_list[count - 1] + 1;

	FATFS *fs;
	DWORD fre_clust, fre_sect, tot_sect;

	/* ドライブ1のボリューム情報と空きクラスタ数を得る */
	res = fatfs_getfree("", &fre_clust, &fs);
	if(FR_OK != res)goto error;

	/* 全セクタ数と空きセクタ数を計算 */
	tot_sect = (fs->n_fatent - 2) * fs->csize;
	fre_sect = fre_clust * fs->csize;

	/* ボリューム全体のサイズと空きのサイズを表示 (512バイト/セクタと仮定) */
	char buf[128];
	sprintf(buf, "%4luk free", fre_sect / 2 / 1024);
	lcd_puts(LCD_LEFT, 2, buf, FCOLOR, BCOLOR);
	sprintf(buf, "%4luk all", tot_sect / 2 / 1024);
	lcd_puts(LCD_LEFT, 3, buf, FCOLOR, BCOLOR);

	return 1;

error:
	return 0;
}

void index_add(int num)
{
	index_list[count++] = num;
	return;
}

int index_count(void)
{
	return count - 1;
}

int index_filenum(int num)
{
	return index_list[num];
}
