#ifndef myjson_h__
#define myjson_h__

#include "cjson.h"
#include "list.h"
#include "bytearray.h"







#define JSON_GET_INT(j,v) {\
  if(j->type==cJSON_Number)\
  {\
    v=j->valueint;\
  }else{\
    DBG_WARN("%s not a int value.",#j);\
  }}

// 获取字符串，如果v==0会申请内存
#define JSON_GET_STR(j,v) {\
  if(j->type==cJSON_String)\
  {\
    int len=strlen(j->valuestring)+1;\
    if(v==0){\
      v=malloc(len);\
    }\
    memcpy(v,j->valuestring,len);\
  }else{\
    DBG_WARN("%s not a str value.",#j);\
  }}



typedef void *(*json_to_obj)(cJSON *j);
typedef void (*del_obj)(void *obj);
typedef struct {
  int obj_size;
  json_to_obj to_obj_fun;
  del_obj del_fun;
  
  // 这些是列表的回调
  sub_fun_def sub;
  del_fun_def del;
}obj_def;


obj_def *obj_int(void);
obj_def *obj_str(void);
list_def *jarray_to_list(cJSON *jarray,obj_def *obj);
cJSON *json_parse(const char *jstr);/*temp_ptr*/





// 参数范围
typedef struct {
  int max;
  int min;
}sch_range;
obj_def *obj_range(void);
int range_in_range(sch_range *r,int num);




// 任务
typedef struct{
  char *brief;
  int task_id;
  int index;
  int param_num;
  list_def *params_info;//str
  list_def *params;//int
  list_def *ranges;//sch_range
  int return_num;
  list_def *returns_info;//str
  int err_jump;
  int retry;
  int failed_code;
  list_def *ret_failed_code;//int
  list_def *ch_errcode;//int
}sch_task;

__packed
typedef struct{
  uint16_t value;
  uint8_t err;
}reurn_item;
__packed
typedef struct{
  uint8_t size;
  uint8_t index;
  uint8_t id;
  uint8_t ack;
  uint8_t exe_err;
  reurn_item items[0];
}task_returns;

obj_def *obj_task(void);
array_def *task_to_array(sch_task *t);
task_returns *task_check_returns(sch_task *t,int ack,array_def *data);




// 主错误代码
typedef struct{
  int err;
  char *info;
  list_def *suberr;//int
}sch_errcode;

obj_def *obj_errcode(void);
int errcode_in_range(sch_errcode *e,int subcode);



typedef struct{
  int plan_id;
  char *brief;
  list_def *slave_soft_versions;//int
  list_def *slave_hard_versions;//int
  int timeout_s;
  int timeout_m;
  int task_id_max;
  list_def *errs;//sch_errcode
  list_def *tasks;//sch_task
  list_def *ch_errcode;//int
}scheme_def;



obj_def *obj_scheme(void);
scheme_def *json_to_scheme(cJSON *j);
void scheme_delete(scheme_def *s);
array_def *scheme_to_byte_array(scheme_def *s);


__packed
typedef struct{
  uint16_t size;
  uint8_t errcode;
  uint8_t data[0];
}scheme_returns;
scheme_returns *scheme_check_returns(scheme_def *s,array_def *data);





#endif

