#include "partition.h"
#include "file.h"
#include "firmware.h"
#include "led.h"
#include "ff.h"

void file_firmware_update(void)
{
    FRESULT ret;
    UINT bc;
    uint32_t idx, byte_cnt;

    ret = f_open(&f, file_name[FILE_IDX_FW], FA_READ);
    if (ret != FR_OK) {
        led_indicate_error();
    }
    idx = 0;
    byte_cnt = 0;
    while (1) {
        ret = f_read(&f, file_buffer, FILE_BUFF_SIZE, &bc);
        if (ret != FR_OK) {
            led_indicate_error();
        }
        /* check whether sector need to be erase */
        if ((byte_cnt == 0) && (bc != 0)) {
            file_secctor_erase(SECTOR_FW0);
        } else if ((byte_cnt == SIZE_FW_SECTOR) && (bc != 0)) {
            file_secctor_erase(SECTOR_FW1);
        } else if ((byte_cnt == SIZE_FW_SECTOR * 2) && (bc != 0)) {
            file_secctor_erase(SECTOR_FW2);
        }
        /* write data to flash */
        file_write_flash(ADDR_FW + idx * FILE_BUFF_SIZE, file_buffer, (uint32_t)bc);
        if ((uint32_t)bc != FILE_BUFF_SIZE) {
            f_close(&f);
            break;
        }
        idx++;
        byte_cnt += FILE_BUFF_SIZE;
    }
}
