#include <rtthread.h>
#include <flashdb.h>
#define FDB_LOG_TAG "[tsdb_sample]"

static uint32_t boot_count = 0;
static time_t boot_time[10] = {0, 1, 2, 3};
static struct fdb_kvdb kvdb = { 0 };
static struct fdb_default_kv_node default_kv_table[] = {
        {"username", "armink ", 8}, /* string KV */
        {"password", "123456", 0}, /* string KV */
        {"boot_count", &boot_count, sizeof(boot_count)}, /* int type KV */
        {"boot_time", &boot_time, sizeof(boot_time)},    /* int array type KV */
};

struct fdb_tsdb tsdb = { 0 };
static int counts = 0;
static struct rt_semaphore tsdb_lock;

static void lock(fdb_db_t db)
{
   // __disable_irq();
	 rt_sem_take(&tsdb_lock, RT_WAITING_FOREVER);
}

static void unlock(fdb_db_t db)
{
  //  __enable_irq();
	 rt_sem_release(&tsdb_lock);
}

static fdb_time_t get_time(void)
{
    /* Using the counts instead of timestamp.
     * Please change this function to return RTC time.
     */
    return counts++;
}

#define THREAD_PRIORITY         3
#define THREAD_STACK_SIZE       800
#define THREAD_TIMESLICE        5

static rt_thread_t tid1 = RT_NULL;

struct env_status {
    int temp;
    int humi;
    int xxx;
    int xxx2;
    int xxx3;
    int xxx4;
    int xxx5;
    int xxx6;
    int xxx7;
};

static bool query_cb(fdb_tsl_t tsl, void *arg)
{
    struct fdb_blob blob;
    struct env_status status;
    fdb_tsdb_t db = arg;

    fdb_blob_read((fdb_db_t) db, fdb_tsl_to_blob(tsl, fdb_blob_make(&blob, &status, sizeof(status))));
    FDB_INFO("[query_cb] queried a TSL: time: %ld, temp: %d, humi: %d\n", tsl->time, status.temp, status.humi);
    return false;
}

static bool query_by_time_cb(fdb_tsl_t tsl, void *arg)
{
    struct fdb_blob blob;
    struct env_status status;
    fdb_tsdb_t db = arg;

    fdb_blob_read((fdb_db_t) db, fdb_tsl_to_blob(tsl, fdb_blob_make(&blob, &status, sizeof(status))));
	FDB_INFO("[query_by_time_cb] queried a TSL: time: %ld, temp: %d, humi: %d status:%d\n", tsl->time, status.temp, status.humi,tsl->status);
    return false;
}

static bool set_status_cb(fdb_tsl_t tsl, void *arg)
{
    fdb_tsdb_t db = arg;

 //   FDB_INFO("set the TSL (time %ld) status from %d to %d\n", tsl->time, tsl->status, FDB_TSL_DELETED);
    fdb_tsl_set_status(db, tsl, FDB_TSL_DELETED);

    return false;
}

void tsdb_sample(fdb_tsdb_t tsdb)
{
    struct fdb_blob blob;
    fdb_tsl_clean(tsdb);
    FDB_INFO("==================== tsdb_sample ====================\n");

    { /* APPEND new TSL (time series log) */
        struct env_status status;
    for(int i=0;i<400;i++)
			{
        /* append new log to TSDB */
        status.temp = i;
        status.humi = 85;
        fdb_tsl_append(tsdb, fdb_blob_make(&blob, &status, sizeof(status)));
       // FDB_INFO("append the new status.temp (%d) and status.humi (%d)  (%d)\n", status.temp, status.humi, i);
				rt_thread_mdelay(10);
			}
    }
		
    { /* QUERY the TSDB by time */
        /* prepare query time (from 1970-01-01 00:00:00 to 2020-05-05 00:00:00) */
        struct tm tm_from = { .tm_year = 1970 - 1900, .tm_mon = 0, .tm_mday = 1, .tm_hour = 0, .tm_min = 0, .tm_sec = 0 };
        struct tm tm_to = { .tm_year = 2020 - 1900, .tm_mon = 4, .tm_mday = 5, .tm_hour = 0, .tm_min = 0, .tm_sec = 0 };
        time_t from_time = mktime(&tm_from), to_time = mktime(&tm_to);
        size_t count;
        /* query all TSL in TSDB by time */
       // fdb_tsl_iter_by_time(tsdb, from_time, to_time, query_by_time_cb, tsdb);
        /* query all FDB_TSL_WRITE status TSL's count in TSDB by time */
        count = fdb_tsl_query_count(tsdb, from_time, to_time, FDB_TSL_WRITE);
        FDB_INFO("query count is: %u\n", count);
    }
		fdb_tsl_iter(tsdb, set_status_cb, tsdb);
		{ /* QUERY the TSDB by time */
        /* prepare query time (from 1970-01-01 00:00:00 to 2020-05-05 00:00:00) */
        struct tm tm_from = { .tm_year = 1970 - 1900, .tm_mon = 0, .tm_mday = 1, .tm_hour = 0, .tm_min = 0, .tm_sec = 0 };
        struct tm tm_to = { .tm_year = 2020 - 1900, .tm_mon = 4, .tm_mday = 5, .tm_hour = 0, .tm_min = 0, .tm_sec = 0 };
        time_t from_time = mktime(&tm_from), to_time = mktime(&tm_to);
        size_t count;
        /* query all TSL in TSDB by time */
       // fdb_tsl_iter_by_time(tsdb, from_time, to_time, query_by_time_cb, tsdb);
        /* query all FDB_TSL_WRITE status TSL's count in TSDB by time */
        count = fdb_tsl_query_count(tsdb, from_time, to_time, FDB_TSL_WRITE);
        FDB_INFO("query count is: %u\n", count);
    }
		
    { /* APPEND new TSL (time series log) */
        struct env_status status;
    for(int i=0;i<400;i++)
			{
        /* append new log to TSDB */
        status.temp = i;
        status.humi = 85;
        fdb_tsl_append(tsdb, fdb_blob_make(&blob, &status, sizeof(status)));
       // FDB_INFO("append the new status.temp (%d) and status.humi (%d)  (%d)\n", status.temp, status.humi, i);
				rt_thread_mdelay(10);
			}
    }
		
    { /* QUERY the TSDB by time */
        /* prepare query time (from 1970-01-01 00:00:00 to 2020-05-05 00:00:00) */
        struct tm tm_from = { .tm_year = 1970 - 1900, .tm_mon = 0, .tm_mday = 1, .tm_hour = 0, .tm_min = 0, .tm_sec = 0 };
        struct tm tm_to = { .tm_year = 2020 - 1900, .tm_mon = 4, .tm_mday = 5, .tm_hour = 0, .tm_min = 0, .tm_sec = 0 };
        time_t from_time = mktime(&tm_from), to_time = mktime(&tm_to);
        size_t count;
        /* query all TSL in TSDB by time */
       // fdb_tsl_iter_by_time(tsdb, from_time, to_time, query_by_time_cb, tsdb);
        /* query all FDB_TSL_WRITE status TSL's count in TSDB by time */
        count = fdb_tsl_query_count(tsdb, from_time, to_time, FDB_TSL_WRITE);
        FDB_INFO("query count is: %u\n", count);
    }
//  
//    { /* QUERY the TSDB by time */
//        /* prepare query time (from 1970-01-01 00:00:00 to 2020-05-05 00:00:00) */
//        struct tm tm_from = { .tm_year = 1970 - 1900, .tm_mon = 0, .tm_mday = 1, .tm_hour = 0, .tm_min = 0, .tm_sec = 0 };
//        struct tm tm_to = { .tm_year = 2020 - 1900, .tm_mon = 4, .tm_mday = 5, .tm_hour = 0, .tm_min = 0, .tm_sec = 0 };
//        time_t from_time = mktime(&tm_from), to_time = mktime(&tm_to);
//        size_t count;
//        
//        /* query all FDB_TSL_WRITE status TSL's count in TSDB by time */
//			//	fdb_tsl_iter(tsdb, set_status_cb, tsdb);
//				count = fdb_tsl_query_count(tsdb, from_time, to_time, FDB_TSL_WRITE);
//        FDB_INFO("query count is: %u\n", count);/* query all TSL in TSDB by time */
//        fdb_tsl_iter_by_time(tsdb, from_time, to_time, query_by_time_cb, tsdb);
//    }		
		
    FDB_INFO("===========================================================\n");
}

void kvdb_type_blob_sample(fdb_kvdb_t kvdb)
{
    struct fdb_blob blob;

    FDB_INFO("==================== kvdb_type_blob_sample ====================\n");

    { /* CREATE new Key-Value */
        int temp_data = 36;

        /* It will create new KV node when "temp" KV not in database.
         * fdb_blob_make: It's a blob make function, and it will return the blob when make finish.
         */
        fdb_kv_set_blob(kvdb, "temp", fdb_blob_make(&blob, &temp_data, sizeof(temp_data)));
        FDB_INFO("create the 'temp' blob KV, value is: %d\n", temp_data);
    }

    { /* GET the KV value */
        int temp_data = 0;

        /* get the "temp" KV value */
        fdb_kv_get_blob(kvdb, "temp", fdb_blob_make(&blob, &temp_data, sizeof(temp_data)));
        /* the blob.saved.len is more than 0 when get the value successful */
        if (blob.saved.len > 0) {
            FDB_INFO("get the 'temp' value is: %d\n", temp_data);
        }
    }

    { /* CHANGE the KV value */
        int temp_data = 38;

        /* change the "temp" KV's value to 38 */
        fdb_kv_set_blob(kvdb, "temp", fdb_blob_make(&blob, &temp_data, sizeof(temp_data)));
        FDB_INFO("set 'temp' value to %d\n", temp_data);
    }
    { /* GET the KV value */
        int temp_data = 0;

        /* get the "temp" KV value */
        fdb_kv_get_blob(kvdb, "temp", fdb_blob_make(&blob, &temp_data, sizeof(temp_data)));
        /* the blob.saved.len is more than 0 when get the value successful */
        if (blob.saved.len > 0) {
            FDB_INFO("get the 'temp' value is: %d\n", temp_data);
        }
    } { /* GET the KV value */
         char temp_data[20] = { 0 };
				 int x=0;
         x=fdb_kv_get_blob(kvdb, "username", fdb_blob_make(&blob, &temp_data, 10));
        if (x > 0) {
					for (int i=0;i<x;i++){
					  FDB_PRINT("0x%x ", temp_data[i]);
				  }
					for (int i=0;i<x;i++){
					  FDB_PRINT("%c ", temp_data[i]);
				  }
				  FDB_PRINT("\n");
        }
				
    }
    { /* DELETE the KV by name */
        fdb_kv_del(kvdb, "temp");
        FDB_INFO("delete the 'temp' finish\n");
    }

    FDB_INFO("===========================================================\n");
}

/* 线程 1 的入口函数 */
static void threadsample_entry(void *parameter)
{
		fdb_err_t result;
	  bool ROLLOVER = true;
	
		rt_sem_init(&tsdb_lock, "tsdb_lock", 1, RT_IPC_FLAG_PRIO);
	
		fdb_tsdb_control(&tsdb, FDB_TSDB_CTRL_SET_LOCK, lock);
		fdb_tsdb_control(&tsdb, FDB_TSDB_CTRL_SET_UNLOCK, unlock);
	
		result = fdb_tsdb_init(&tsdb, "test", "ts_pf", get_time, 128, NULL);
	
	  if (result != FDB_NO_ERR) {
      return ;
		}
		fdb_tsdb_control(&tsdb, FDB_TSDB_CTRL_SET_ROLLOVER, &ROLLOVER);
		/* read last saved time for simulated timestamp */
		fdb_tsdb_control(&tsdb, FDB_TSDB_CTRL_GET_LAST_TIME, &counts);
	
	
	  struct fdb_default_kv default_kv;

    default_kv.kvs = default_kv_table;
    default_kv.num = sizeof(default_kv_table) / sizeof(default_kv_table[0]);
	  fdb_kvdb_control(&kvdb, FDB_KVDB_CTRL_SET_LOCK, lock);
    fdb_kvdb_control(&kvdb, FDB_KVDB_CTRL_SET_UNLOCK, unlock);
	
	  result = fdb_kvdb_init(&kvdb, "env", "kv", &default_kv, NULL);

    if (result != FDB_NO_ERR) {
      return ;
		}
    kvdb_type_blob_sample(&kvdb);
		/* run TSDB sample */
		tsdb_sample(&tsdb);
}

void threadsample_init(void)
{
    tid1 = rt_thread_create("threadsample",
                            threadsample_entry, RT_NULL,
                            THREAD_STACK_SIZE,
                            THREAD_PRIORITY, THREAD_TIMESLICE);

    /* 如果获得线程控制块，启动这个线程 */
    if (tid1 != RT_NULL)
        rt_thread_startup(tid1);
}
