/*
 * Copyright (c) 2012-2014 Wind River Systems, Inc.
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <zephyr/zephyr.h>
#include <kernel.h>
#include <storage/flash_map.h>

#include <img_mgmt/img_mgmt_impl.h>
#include <img_mgmt/img_mgmt.h>

#include <logging/log.h>
LOG_MODULE_REGISTER(main, 4);

#define S0_ID FLASH_AREA_ID(s0)
#define S1_ID FLASH_AREA_ID(s1)

#define S0_SIZE FLASH_AREA_SIZE(s0)
#define S1_SIZE FLASH_AREA_SIZE(s1)

static int init(uint8_t id)
{
    const struct flash_area *fa;

    int err = flash_area_open(id, &fa);
    if (err) {
        LOG_ERR("err: %d.", err);
    }

    uint32_t align = flash_area_align(fa);

    LOG_WRN("align: 0x%x", align);
    flash_area_close(fa);
    return err;
}

static void erase(uint8_t id, size_t len)
{
    const struct flash_area *fa;

    int err = flash_area_open(id, &fa);
    if (err) {
        LOG_ERR("flash_area_open err: %d.", err);
        return;
    }

    uint8_t buf[32] = { 0 };

    err = flash_area_read(fa, 0, buf, sizeof(buf));
    if (err) {
        LOG_ERR("flash_area_read err: %d.", err);
        return;
    }

    LOG_HEXDUMP_INF(buf, sizeof(buf), "read:");

    LOG_WRN("len: 0x%x.", len);
    LOG_WRN("fa_size: 0x%x.", fa->fa_size);

    err = flash_area_erase(fa, 0, len);
    if (err) {
        LOG_ERR("flash_area_erase err: %d.", err);
        return;
    }

    err = flash_area_read(fa, 0, buf, sizeof(buf));
    if (err) {
        LOG_ERR("flash_area_read err: %d.", err);
        return;
    }

    LOG_HEXDUMP_INF(buf, sizeof(buf), "read:");

    flash_area_close(fa);
}


void main(void)
{
    init(S0_ID);
    init(S1_ID);
    erase(S0_ID, S0_SIZE);
    erase(S1_ID, S1_SIZE);

    // int rc = img_mgmt_impl_erase_slot();
    // LOG_INF("img_mgmt_impl_erase_slot: %d.", rc);

    // rc = img_mgmt_slot_in_use(0);
    // LOG_INF("0img_mgmt_slot_in_use: %d.", rc);

    // rc = img_mgmt_slot_in_use(1);
    // LOG_INF("1img_mgmt_slot_in_use: %d.", rc);

    // rc = img_mgmt_state_confirm();
    // LOG_INF("img_mgmt_state_confirm: %d.", rc);

    LOG_INF("Hello World! %s.", CONFIG_BOARD);
}
