#include "log_api.h"
#include "log.h"
#include "rtc.h"
#include "ringfs.h"
#include "spi_flash.h"
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
#include "rtc.h"
#include <string.h>
#include <stdio.h>
#include <inttypes.h>

#undef DBG
#define DBG if(1)

extern struct ringfs fs_archive;

extern SemaphoreHandle_t log_mutex;

static archive_entry_t archive_entry;


//
void log_get_entry_count(void)
{
    int count_flash = 0;
    
    count_flash = ringfs_count_exact(&fs_archive);
    printf("Count archive entry: %u\r\n", count_flash);
}

//
int log_get_entry(uint32_t index, struct ringfs *fs, void *entry)
{
    archive_entry_t *ent = entry;
    
	int start = ringfs_count_estimate(fs);
    
    fs->cursor_position =  start - (index - 1) - 1;
    
	if (fs->cursor_position < 0)
		return -1;
	else
    {
		fs->cursor.sector = (fs->read.sector + fs->cursor_position/fs->slots_per_sector)%fs->flash->sector_count;
		fs->cursor.slot = fs->cursor_position%fs->slots_per_sector;
	}
    
    log_fetch(entry, ARCHIVE_ENTRY, portMAX_DELAY);
#if 1
    printf("[entry] timestamp = % " PRId64 ", value = %u, crc = %u\r\n", 
           ent->timestamp, ent->input_value, ent->crc);
#endif    
    return 0;
}

//
int mb_log_get_entry(uint8_t *buf, uint16_t entry_index)
{
    uint8_t pack_len = 3;
    buf[2] = 0x06;  // Reference type
    
    log_get_entry(entry_index, &fs_archive, &archive_entry);
#if 0    
    printf("[entry] timestamp = % " PRId64 ", value = %u, crc = %u\r\n", 
           archive_entry.timestamp, archive_entry.input_value, archive_entry.crc);
#endif    
    memcpy(&buf[3], &archive_entry, sizeof(archive_entry_t));
    pack_len += sizeof(archive_entry_t);
    
    buf[0] = pack_len; // Resp. data length, 1 byte
    buf[1] = pack_len; // File Resp. length, 1 byte
    
    return pack_len;
}

