#include "ansjer_ai_cfg.h"
#include <iostream>
#include <string.h>

char* load_file(char const* path)
{
    char* buffer = 0;
    long length;
    FILE * f = fopen (path, "rb"); //was "rb"

    if (f)
    {
      fseek (f, 0, SEEK_END);
      length = ftell (f);
      fseek (f, 0, SEEK_SET);
      buffer = (char*)malloc ((length+1)*sizeof(char));
      if (buffer)
      {
        fread (buffer, sizeof(char), length, f);
      }
      fclose (f);
    }
    buffer[length] = '\0';
    // for (int i = 0; i < length; i++) {
    //     printf("buffer[%d] == %c\n", i, buffer[i]);
    // }
    //printf("buffer = %s\n", buffer);

    return buffer;
}


int read_Asj_Ai_Json (void *hdl, char *filename){
	char *json_file_str = load_file(filename);
	printf("%s",json_file_str);
	Asj_Ai_Cfg_t *ai_config = (Asj_Ai_Cfg_t *)hdl;
	
	json_t mem[64];
	json_t const* json = json_create(json_file_str, mem, sizeof mem / sizeof *mem );

    json_t const* property = json_getProperty(json, "property");
	json_t const* model_type = json_getProperty(property, "model_type");
	ai_config->property.model_type = json_getValue(model_type);
	json_t const* ezb_model_path = json_getProperty(property, "ezb_model_path");
	strcpy(ai_config->property.ezbStr, json_getValue(ezb_model_path ));
	json_t const* ezb_bin_path = json_getProperty(property, "ezb_bin_path");
	strcpy(ai_config->property.binStr, json_getValue(ezb_bin_path ));
	json_t const* yolo_anchor = json_getProperty(property, "yolo_anchor");
	int index = 0;
	for(json_t const* i = json_getChild(yolo_anchor); i != 0; i = json_getSibling(i)) {
		ai_config->property.anchors[index] = json_getInteger(i);
		index++;
    }
	index = 0;
	json_t const* label = json_getProperty(property, "label" );
	for(json_t const* i = json_getChild(label); i != 0; i = json_getSibling(i)) {
		ai_config->property.label.push_back(json_getValue(i));
		index++;
    }
	index = 0;

	json_t const* output_blob_names = json_getProperty(property, "output_blob_names");
	for(json_t const* i = json_getChild(output_blob_names); i != 0; i = json_getSibling(i)) {
		ai_config->property.yolo_outputs_name.push_back( json_getValue(i));
		index++;
    }

	json_t const* need_nu_freq = json_getProperty(property, "need_nu_freq" );

	ai_config->property.need_nu_freq = json_getBoolean(json_getProperty(property, "need_nu_freq"));
    ai_config->property.freq_nu = json_getInteger(json_getProperty(property,"freq_nu"));
	ai_config->property.need_vu_freq = json_getBoolean(json_getProperty(property,"need_vu_freq"));
    ai_config->property.freq_vu = json_getInteger(json_getProperty(property,"freq_vu"));
	json_t const* class_attrs_all = json_getProperty( json, "class_attrs_all");
	ai_config->class_attrs_all.conf_thresh = json_getReal(json_getProperty(class_attrs_all,"pre_cluster_threshold"));
	ai_config->class_attrs_all.iou_thresh = json_getReal(json_getProperty(class_attrs_all,"nms_iou_threshold"));
	return 1;
}
