/******************************************************************************
 * 2016 ideasX (Tyler Berezowsky)
 *
 * FileName: config.c
 *
 * Description: This file is going to need alot of help by a C wizard, but it currently works...I think.
 *
 *     2016/8/8, v1.0 created this file
*******************************************************************************
*
* Copyright (c) 2014-2015, Tuan PM <tuanpm at live dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form 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.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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 "ets_sys.h"
#include "os_type.h"
#include "mem.h"
#include "osapi.h"
#include "user_interface.h"

#include "mqtt/mqtt.h"
#include "modules/config.h"
#include "user_config.h"
#include "driver/uart.h"

/* CFG_LOCATION: 0x2
 * (CFG_LOCATION + 0)*0x1000 = 0x2000
 * (CFG_LOCATION + 1)*0x1000 = 0x3000
 * (CFG_LOCATION + 2)*0x1000 = 0x4000
 * (CFG_LOCATOIN + 3)*0x1000 = 0x5000
 *
 */



SYSCFG sysCfg;
SAVE_FLAG saveFlag;
MQTT_TOPICS mqttTopics;

void ICACHE_FLASH_ATTR cfg_save()
{
    #if CONFIG_DEBUG
    uart0_sendStr("Writing New Default Module Configuration\r\n");
    #endif
    spi_flash_read((CFG_LOCATION + 3) * SPI_FLASH_SEC_SIZE,		    // read config sector 3 for
                       (uint32 *)&saveFlag, sizeof(SAVE_FLAG));		// saveFlag

    if (saveFlag.flag == 0) {
    spi_flash_erase_sector(CFG_LOCATION + 1); 					// erase config sector 1
    spi_flash_write((CFG_LOCATION + 1) * SPI_FLASH_SEC_SIZE,	// write sysCfg in config sector 1
    (uint32 *)&sysCfg, sizeof(SYSCFG));
    saveFlag.flag = 1;											// set saveFlag.flag
    spi_flash_erase_sector(CFG_LOCATION + 3);					// erase config sector 3
    spi_flash_write((CFG_LOCATION + 3) * SPI_FLASH_SEC_SIZE,	// write saveFlag to config sector 3
    (uint32 *)&saveFlag, sizeof(SAVE_FLAG));
    }
    else {
    spi_flash_erase_sector(CFG_LOCATION + 0);					// erase config sector 0 for sysCfg
    spi_flash_write((CFG_LOCATION + 0) * SPI_FLASH_SEC_SIZE,			// write sysCfg to config sector 0
    (uint32 *)&sysCfg, sizeof(SYSCFG));
    saveFlag.flag = 0;								// clear saveFlag.flag
    spi_flash_erase_sector(CFG_LOCATION + 3);					// erase config sector 3
    spi_flash_write((CFG_LOCATION + 3) * SPI_FLASH_SEC_SIZE,			// write saveFlag to config sector 3
    (uint32 *)&saveFlag, sizeof(SAVE_FLAG));
    }
}

void ICACHE_FLASH_ATTR cfg_load()
{
    #if CONFIG_DEBUG
    uart0_sendStr("Loading Default Module Configuration...\r\n");
    #endif
    spi_flash_read((CFG_LOCATION + 3) * SPI_FLASH_SEC_SIZE,			// read save Flag to config sector 3
       (uint32 *)&saveFlag, sizeof(SAVE_FLAG));
    if (saveFlag.flag == 0) {						// if saveFlag.flag == 0
    spi_flash_read((CFG_LOCATION + 0) * SPI_FLASH_SEC_SIZE,		// write sysCfg to config sector 0
       (uint32 *)&sysCfg, sizeof(SYSCFG));
    } else {								// if saveFlag.flag == 1
    spi_flash_read((CFG_LOCATION + 1) * SPI_FLASH_SEC_SIZE,		// write sysCfg to config sector 1
       (uint32 *)&sysCfg, sizeof(SYSCFG));
    }
    if(sysCfg.cfg_holder != CFG_HOLDER){			// if sysCfg doesn't contain the proper check value
    os_memset(&sysCfg, 0x00, sizeof sysCfg);	// clear sysCfg


    sysCfg.cfg_holder = CFG_HOLDER;

    os_sprintf(sysCfg.sta_ssid[0], "%s", STA_SSID);				// load STA_SSID into sysCfg
    os_sprintf(sysCfg.sta_pwd[0], "%s", STA_PASS);				// load STA_PASS into sysCfg
    sysCfg.sta_type[0] = STA_TYPE;								// load STA_TYPE into sysCfg
    sysCfg.registered_stations = 1;
    sysCfg.current_station = 0;

    wifi_get_macaddr(STATION_IF, sysCfg.device_id);
    os_sprintf(sysCfg.mqtt_host, "%s", MQTT_HOST);							// load MQTT_HOST
    sysCfg.mqtt_port = MQTT_PORT;											// load MQTT_PORT
    os_sprintf(sysCfg.mqtt_user, "%s", MQTT_USER);							// load MQTT_USER
    os_sprintf(sysCfg.mqtt_pass, "%s", MQTT_PASS);							// load MQTT_PASS

    sysCfg.security = DEFAULT_SECURITY;										/* default non ssl */
    sysCfg.mqtt_keepalive = MQTT_KEEPALIVE;									// load MQTT_KEEPALIVE

    os_sprintf(sysCfg.ota_host, "%s", OTA_HOST);
    sysCfg.ota_port = OTA_PORT;

    cfg_save();
    }

    sysCfg.module_state.all_flags = 0U; 					// clear all flags
    sysCfg.uart_state = 0;
    sysCfg.module_state.alive = true;

    os_sprintf(mqttTopics.data, "/encoder/" MACSTR "/data", MAC2STR(sysCfg.device_id));
    os_sprintf(mqttTopics.command, "/encoder/" MACSTR "/command", MAC2STR(sysCfg.device_id));
    os_sprintf(mqttTopics.health, "/encoder/" MACSTR "/health", MAC2STR(sysCfg.device_id));

}