#include <stdio.h>
#include <string.h>
#include "yolo.h"
#include "ax_test_utils.h"
#include <vx_log.h>
#include <iostream>

int get_yuv(ezax_img_t &input){
    int y_size = 384 * 640;
    int uv_size = y_size / 2;

    FILE *input_file = NULL;
    char *input_file_name = (char *)"images.yuv";
    input_file = fopen(input_file_name, "rb");
	if (input_file == NULL) {
		VX_LOG("%s fopen file %s error\n", __FUNCTION__, input_file_name);
		return 1;
	}

    memset(&input, 0, sizeof(ezax_img_t));
    input.img_handle.fmt = EZAX_YUV420_SP;
    input.img_handle.w   = 640;
	input.img_handle.h   = 384;
	input.img_handle.c   = 2;
	input.img_handle.stride   = 0;

    input.roi.x0 = 0;
	input.roi.y0 = 0;
	input.roi.x1 = 640;
	input.roi.y1 = 384;
    input.img_handle.pVir = ax_malloc_uncache(&input.img_handle.pPhy, y_size + uv_size);
	input.img_handle.pVir_UV = (void *)((char *)input.img_handle.pVir + y_size);
	input.img_handle.pPhy_UV = input.img_handle.pPhy + y_size;

    VX_LOG("%s y_size %d uv_size %d\n", __FUNCTION__, y_size, uv_size);
	VX_LOG("%s input.img_handle.pVir : %p\n", __FUNCTION__, input.img_handle.pVir);
	VX_LOG("%s input.img_handle.pPhy : %x\n", __FUNCTION__, input.img_handle.pPhy);

    int len;
    len = fread(input.img_handle.pVir, 1, y_size + uv_size, input_file);
    if (len != (y_size + uv_size)) {
        VX_LOG("%s fread error.\n");
        return -1;
    }
    
    VX_LOG("%s fread success\n", __FUNCTION__);
    
    return 0;
}

int yolo_test(){
    int state;
    ezax_img_t input;
    ezax_boxes_t pOut;
    ezax_custom_det_cfg_t cfg;
    void *yolo_hdl;
    float conf_thresh, iou_thresh;

    conf_thresh = 0.35;
    iou_thresh = 0.25;

    cfg.width = 640;
    cfg.height = 384;

    VX_LOG("%s begin yolo_test.\n", __FUNCTION__);
    yolo_hdl = nna_custom_det_open(&cfg);
    if (yolo_hdl == NULL) {
		VX_LOG("%s yolov_hdl open error\n", __FUNCTION__);
		return 0;
	}
    VX_LOG("%s nna_custom_det_open success.\n", __FUNCTION__);

    state = get_yuv(input);
    if (state != VX_SUCCESS) {
		VX_LOG("%s get_yuv error\n", __FUNCTION__);
		return 0;
	}
    
    pOut.pRect = (ezax_rt_t *)ax_malloc_virt(sizeof(ezax_rt_t) * MAX_CLASSIFICATION_DET_NUM);
    pOut.num   = 0;
    state = nna_custom_det_process(yolo_hdl, &input, &pOut, conf_thresh, iou_thresh);
    if (state != VX_SUCCESS) {
		VX_LOG("%s nna_yolo_det_process error\n", __FUNCTION__);
		return 0;
	}
    std::cout << __LINE__ << std::endl;
    state = nna_custom_det_close(yolo_hdl);
    if (state != VX_SUCCESS) {
		VX_LOG("%s nna_yolo_det_close error\n", __FUNCTION__);
		return 0;
	}
    // free(&input);
    // free(pOut.pRect);
    std::cout << __LINE__ << std::endl;
    while (1)
    {
        /* code */
    }
    return 1;
}

int main(int argc, char *argv[]){
	yolo_test();
	return 0;
}