#include "drv_wdog.h"

#include "bsp_flash.h"

#include "kit_time.h"
#include "kit_data.h"
#include "kit_debug.h"


kit_ret_e bsp_flash_erase_page(flash_Item_t *item, uint32_t addr, uint32_t len)
{
    uint32_t cnt;
    kit_ret_e res = kKit_Ret_ParamErr;
    if(item != NULL)
    {
        cnt = len / drv_flash_get_page_size(item);
        if (len % drv_flash_get_page_size(item) != 0)
        {
            cnt += 1;
        }
        res = flash_series_erase_page(item, addr, cnt);
    }
    return res;
}

kit_ret_e bsp_flash_write_data_u32(flash_Item_t *item, uint32_t addr, uint8_t* buf, uint32_t len)
{
    uint32_t i, data;
    kit_ret_e res = kKit_Ret_ParamErr;
    
    KIT_ASSERT_PARAM((item != NULL) && ((addr % 4) == 0) && (buf != NULL) && ((len % 4) == 0));    
     
    if((item != NULL) && ((addr % 4) == 0) && (buf != NULL) && ((len % 4) == 0))
    {
        len >>= 2;
        for(i = 0; i < len; i++)
        {
            data = ((uint32_t *)buf)[i];
            res = drv_flash_write_u32(item, addr + (i << 2), data);
            if(res != kKit_Ret_Ok)
                break;
                   
            if(((i + 1) % 300) == 0)
                drv_wdog_feed();
        }
    }

    return res;
}

bool bsp_flash_check_write_u32(flash_Item_t *item, uint32_t addr, uint32_t value)
{
    uint32_t read = value + 1;
    
    KIT_ASSERT_PARAM(item != NULL);
    if(item != NULL)
    {
        drv_flash_write_u32(item, addr, value);
        drv_flash_read_u32(item, addr, &read);
    }
    return (read == value);
}

bool bsp_drv_flash_write_u32_check(flash_Item_t *item, uint32_t *addr, uint32_t value)
{
	bool res = false;
    
    KIT_ASSERT_PARAM((item != NULL) && (addr != NULL));
    if((item != NULL) && (addr != NULL))
    {
        res = bsp_flash_check_write_u32(item, *addr, value);
        *addr += 4;
    }

	return res;
}
