#include "drv_wdog.h"

#include "bsp_flash.h"

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


KitResult flash_erase_page_by_len(FlashItem *item, uint32_t addr, uint32_t len)
{
    uint32_t cnt;
    KitResult res = kKitResult_ParamErr;
    if(item != NULL)
    {
        cnt = len / flash_get_page_size(item);
        if (len % flash_get_page_size(item) != 0)
        {
            cnt += 1;
        }
        res = flash_series_erase_page(item, addr, cnt);
    }
    return res;
}

KitResult flash_series_write_u32(FlashItem *item, uint32_t addr, uint8_t* buf, uint32_t len)
{
    uint32_t i, data;
    KitResult res = kKitResult_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 = flash_write_u32(item, addr + (i << 2), data);
            if(res != kKitResult_Ok)
                break;
                   
            if(((i + 1) % 300) == 0)
                drv_wdog_feed();
        }
    }

    return res;
}

bool flash_checken_write_u32(FlashItem *item, uint32_t addr, uint32_t value)
{
    uint32_t read = value + 1;
    
    KIT_ASSERT_PARAM(item != NULL);
    if(item != NULL)
    {
        flash_write_u32(item, addr, value);
        flash_read_u32(item, addr, &read);
    }
    return (read == value);
}

bool flash_write_u32_with_check_in(FlashItem *item, uint32_t *addr, uint32_t value)
{
	bool res = false;
    
    KIT_ASSERT_PARAM((item != NULL) && (addr != NULL));
    if((item != NULL) && (addr != NULL))
    {
        res = flash_checken_write_u32(item, *addr, value);
        *addr += 4;
    }

	return res;
}
