/**
 * Copyright (c) 2017 - 2021, Nordic Semiconductor ASA
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 *
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 *
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <stdint.h>
#include <string.h>
#include "nrf.h"
#include "nordic_common.h"
#ifdef SOFTDEVICE_PRESENT
#include "nrf_sdh.h"
#include "nrf_sdh_ble.h"
#else
#include "nrf_drv_clock.h"
#endif
#include "fds.h"
#include "app_timer.h"
#include "app_error.h"
#include "nrf_cli.h"
#include "fds_example.h"

#define NRF_LOG_MODULE_NAME app
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_gpio.h"
#include "nrf_delay.h"

#define KEY_PIN_1  13
#define LED_PIN_1  17
#define LED_PIN_2  18
#define LED_PIN_3  19

/* A tag identifying the SoftDevice BLE configuration. */
#define APP_BLE_CONN_CFG_TAG    1

/* Array to map FDS events to strings. */
static char const * fds_evt_str[] =
{
    "FDS_EVT_INIT",
    "FDS_EVT_WRITE",
    "FDS_EVT_UPDATE",
    "FDS_EVT_DEL_RECORD",
    "FDS_EVT_DEL_FILE",
    "FDS_EVT_GC",
};

typedef struct
{
    unsigned long p_v;
    signed char scBleAddr[6];
    unsigned long ulB;
    unsigned long eBmo;
    unsigned long ulNeedCharge;
    signed short sxyz[3];
    signed short ssThd;
    unsigned short usAdcValue;
    unsigned char aucSN[20];
    unsigned char ucBLight;
    unsigned long flash_erase_flag;
    #define GET_BAR_STATE(states, bar_index)    ((states>>(bar_index<<1)) & 0x3) // 2 bit for each bar
    unsigned long c_f_t_s[6][7];   
    unsigned char brightness[6];    
    unsigned long ulChecksum;
    unsigned char publicNet;
    unsigned char netID[4];
    #define getCustomizedSetting(xxx)  gtPara.xxx
	unsigned char Profiles[4];
	unsigned char mode;
	unsigned char profile_nn;
    unsigned char netID_e;
    unsigned char PowerOff;
    unsigned char enabledHallSensor;    
}T_Para; 

T_Para gtPara;
static T_Para gtStorePara = 
{
	.p_v = 0x01010102,
	.ulB = 0,
	.eBmo = 0x02,
	.ulNeedCharge = 0,
	.sxyz[0] = 100,
	.sxyz[1] = 0,
	.sxyz[2] = 0,
	.ssThd = -3500,
	.ucBLight = 70,
	.publicNet = 0,
	.netID_e = 0,
	.PowerOff = 0,
};

/* A record containing dummy configuration data. */
static fds_record_t const gtPara_record =
{
    .file_id           = CONFIG_FILE,
    .key               = CONFIG_REC_KEY,
    .data.p_data       = &gtStorePara,
    /* The length of a record is always expressed in 4-byte units (words). */
    .data.length_words = (sizeof(gtStorePara) + sizeof(uint32_t) - 1) / sizeof(uint32_t),
};

/* Keep track of the progress of a delete_all operation. */
static struct
{
    bool delete_next;   //!< Delete next record.
    bool pending;       //!< Waiting for an fds FDS_EVT_DEL_RECORD event, to delete the next record.
} m_delete_all;

/* Flag to check fds initialization. */
static bool volatile m_fds_initialized;


const char *fds_err_str(ret_code_t ret)
{
    /* Array to map FDS return values to strings. */
    static char const * err_str[] =
    {
        "FDS_ERR_OPERATION_TIMEOUT",
        "FDS_ERR_NOT_INITIALIZED",
        "FDS_ERR_UNALIGNED_ADDR",
        "FDS_ERR_INVALID_ARG",
        "FDS_ERR_NULL_ARG",
        "FDS_ERR_NO_OPEN_RECORDS",
        "FDS_ERR_NO_SPACE_IN_FLASH",
        "FDS_ERR_NO_SPACE_IN_QUEUES",
        "FDS_ERR_RECORD_TOO_LARGE",
        "FDS_ERR_NOT_FOUND",
        "FDS_ERR_NO_PAGES",
        "FDS_ERR_USER_LIMIT_REACHED",
        "FDS_ERR_CRC_CHECK_FAILED",
        "FDS_ERR_BUSY",
        "FDS_ERR_INTERNAL",
    };

    return err_str[ret - NRF_ERROR_FDS_ERR_BASE];
}

static bool volatile m_fds_writeflag;
static void fds_evt_handler(fds_evt_t const * p_evt)
{
    if (p_evt->result == NRF_SUCCESS)
    {
        NRF_LOG_GREEN("Event: %s received (NRF_SUCCESS)",
                      fds_evt_str[p_evt->id]);
    }
    else
    {
        NRF_LOG_GREEN("Event: %s received (%s)",
                      fds_evt_str[p_evt->id],
                      fds_err_str(p_evt->result));
    }

    switch (p_evt->id)
    {
        case FDS_EVT_INIT:
            if (p_evt->result == NRF_SUCCESS)
            {
                m_fds_initialized = true;
            }
            break;
        case FDS_EVT_UPDATE:
        case FDS_EVT_WRITE:
        {
            if (p_evt->result == NRF_SUCCESS)
            {
                m_fds_writeflag = true;
                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->write.record_id);
                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->write.file_id);
                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->write.record_key);
            }
        } break;

        case FDS_EVT_DEL_RECORD:
        {
            if (p_evt->result == NRF_SUCCESS)
            {
                NRF_LOG_INFO("Record ID:\t0x%04x",  p_evt->del.record_id);
                NRF_LOG_INFO("File ID:\t0x%04x",    p_evt->del.file_id);
                NRF_LOG_INFO("Record key:\t0x%04x", p_evt->del.record_key);
            }
            m_delete_all.pending = false;
        } break;

        default:
            break;
    }
}


/**@brief   Begin deleting all records, one by one. */
void delete_all_begin(void)
{
    m_delete_all.delete_next = true;
}


/**@brief   Process a delete all command.
 *
 * Delete records, one by one, until no records are left.
 */
void delete_all_process(void)
{
    if (   m_delete_all.delete_next
        & !m_delete_all.pending)
    {
        NRF_LOG_INFO("Deleting next record.");

        m_delete_all.delete_next = record_delete_next();
        if (!m_delete_all.delete_next)
        {
            NRF_LOG_CYAN("No records left to delete.");
        }
    }
}


#ifdef SOFTDEVICE_PRESENT
/**@brief   Function for initializing the SoftDevice and enabling the BLE stack. */
static void ble_stack_init(void)
{
    ret_code_t rc;
    uint32_t   ram_start;

    /* Enable the SoftDevice. */
    rc = nrf_sdh_enable_request();
    APP_ERROR_CHECK(rc);

    rc = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
    APP_ERROR_CHECK(rc);

    rc = nrf_sdh_ble_enable(&ram_start);
    APP_ERROR_CHECK(rc);
}
#else
static void clock_init(void)
{
    /* Initialize the clock. */
    ret_code_t rc = nrf_drv_clock_init();
    APP_ERROR_CHECK(rc);

    nrf_drv_clock_lfclk_request(NULL);

    /* Wait for the clock to be ready. */
    while (!nrf_clock_lf_is_running()) {;}
}
#endif

APP_TIMER_DEF(m_1ms_timer_id);                                                      /**< 1ms timer. */

unsigned long gulTimerCnt1ms;
static unsigned long sgulCalibrate = 0;

void clock1ms_timeout_handler(void * p_context) {
    gulTimerCnt1ms++; if(gulTimerCnt1ms == 500){sgulCalibrate = 1; gulTimerCnt1ms = 0;}
}
/**@brief   Initialize the timer. */
static void timer_init(void)
{
    ret_code_t err_code = app_timer_init();
    APP_ERROR_CHECK(err_code);
    
	err_code = app_timer_create(&m_1ms_timer_id,
                                APP_TIMER_MODE_REPEATED,
                                clock1ms_timeout_handler);
    APP_ERROR_CHECK(err_code);
		
    app_timer_start(m_1ms_timer_id,10,NULL);
}


/**@brief   Initialize logging. */
static void log_init(void)
{
    ret_code_t rc = NRF_LOG_INIT(NULL);
    APP_ERROR_CHECK(rc);
}


/**@brief   Sleep until an event is received. */
static void power_manage(void)
{
#ifdef SOFTDEVICE_PRESENT
    (void) sd_app_evt_wait();
#else
    __WFE();
#endif
}

#define BUTTON_PRESSED 1
#define BUTTON_RELEASED 0
int read_button_state() {
   if(nrf_gpio_pin_read(KEY_PIN_1)){
    return BUTTON_RELEASED;
   }else{
       return BUTTON_PRESSED;
   }
}

// key press detect
bool detect_short_press() {
    static bool button_state = BUTTON_RELEASED;
    static bool button_was_pressed = false;
    
    int current_state = read_button_state();

    if (current_state == BUTTON_PRESSED && button_state == BUTTON_RELEASED) {
        button_was_pressed = true;
    }
    
    if (current_state == BUTTON_RELEASED && button_state == BUTTON_PRESSED) {
        if (button_was_pressed) {
            button_was_pressed = false;
            return true;
        }
    }

    button_state = current_state;
    
    return false;
}


/**@brief   Wait for fds to initialize. */
static void wait_for_fds_ready(void)
{
    while (!m_fds_initialized)
    {
        power_manage();
    }
}

fds_stat_t stat2 = {0};
void flash_store(void)
{
		ret_code_t err_code;
		fds_record_desc_t desc = {0};//The descriptor structure used to manipulate the record is zeroed out
        fds_find_token_t  tok  = {0};//The token that saves the key is cleared
		//fds_record_t record = {0};
   
        //gtStorePara = gtPara;
        memcpy(&gtStorePara, &gtPara, sizeof(gtPara));
        
        //write_flag set
        m_fds_writeflag = false;
		// Check the record exists
		err_code = fds_record_find( CONFIG_FILE, CONFIG_REC_KEY, &desc, &tok );
	
		/* Write the updated record to flash.*/
		if( err_code == NRF_SUCCESS){
            err_code = fds_record_update(&desc, &gtPara_record);
            if(err_code == FDS_ERR_NO_SPACE_IN_FLASH){
                err_code = fds_gc();
                APP_ERROR_CHECK(err_code);
            }               
    
            err_code = fds_stat(&stat2);
            if(stat2.valid_records == 0x02)
            {
                nrf_gpio_pin_clear(LED_PIN_1);
                while(1);
            }
            APP_ERROR_CHECK(err_code);				
		}else{
            err_code = fds_record_write(&desc, &gtPara_record);//Write records and data. Descriptor, used later to access the record ID
            APP_ERROR_CHECK(err_code);		
        }		
}

int main(void)
{
    ret_code_t rc;

#ifdef SOFTDEVICE_PRESENT
    ble_stack_init();
#else
    clock_init();
#endif

    timer_init();
    log_init();

    //led
    nrf_gpio_cfg_output(LED_PIN_1);
    nrf_gpio_pin_set(LED_PIN_1);

    nrf_gpio_cfg_output(LED_PIN_2);
    nrf_gpio_pin_set(LED_PIN_2);
  
    nrf_gpio_cfg_output(LED_PIN_3);
    nrf_gpio_pin_set(LED_PIN_3);
    //key
    nrf_gpio_cfg_input(KEY_PIN_1,NRF_GPIO_PIN_PULLUP);
    
    NRF_LOG_INFO("FDS example started.")

    /* Register first to receive an event when initialization is complete. */
    (void) fds_register(fds_evt_handler);

    NRF_LOG_INFO("Initializing fds...");

    rc = fds_init();
    APP_ERROR_CHECK(rc);

    /* Wait for fds to initialize. */
    wait_for_fds_ready();


    fds_stat_t stat = {0};

    rc = fds_stat(&stat);
    APP_ERROR_CHECK(rc);

    NRF_LOG_INFO("Found %d valid records.", stat.valid_records);
    NRF_LOG_INFO("Found %d dirty records (ready to be garbage collected).", stat.dirty_records);

    fds_record_desc_t desc = {0};
    fds_find_token_t  tok  = {0};

    rc = fds_record_find(CONFIG_FILE, CONFIG_REC_KEY, &desc, &tok);

     if (rc == NRF_SUCCESS)//if find successful
        {
            /* A config file is in flash. Let's update it. */
            fds_flash_record_t config = {0};//res

            /* Open the record and read its contents. */
            rc = fds_record_open(&desc, &config);//open record to read data

            APP_ERROR_CHECK(rc); 
            /* Copy the configuration from flash into m_dummy_cfg*/
            memcpy(&gtPara, config.p_data, sizeof(gtPara));

            //data = (uint32_t *)config.p_data;
                    
            /* Close the record when done reading. */
            rc = fds_record_close(&desc);//close record
            APP_ERROR_CHECK(rc);
        }else{
            rc = fds_record_write(&desc, &gtPara_record);//Write records and data. Descriptor, used later to access the record ID
            APP_ERROR_CHECK(rc);		
        }
    /* Enter main loop. */
    for (;;)
    {
        if(sgulCalibrate){
            sgulCalibrate = 0;
            flash_store();
            nrf_gpio_pin_toggle(LED_PIN_2);
        }
        
        //The short press here is actually to simulate the sudden update data behavior(Update flash behavior after charging reset of our device)
        if(detect_short_press()){
            flash_store();  
            nrf_gpio_pin_toggle(LED_PIN_3);
        }            
        
    }
}


/**
 * @}
 */
