#include <stdlib.h>
#include "hal_interface_video.h"
#include "list.h"
#include "hthread.h"
#include "hlog.h"

typedef struct{
	struct list_head    	 link;
	video_attr_st			 attr;
	hal_video_frame_callback cb;
}video_ins;

static struct list_head s_vlist = LIST_HEAD_INIT(s_vlist);

static void * hal_video_polling_task(void *arg)
{
	uint32_t ret;
	uint32_t get;
	while(1){
		video_frame frame;
		get = 0;
		struct list_head *pos, *n;
		list_for_each_safe(pos, n, &s_vlist){
			video_ins *video = list_entry(pos, video_ins, link);
			ret = hal_video_get_frame(video->attr.stream_chn, &frame, 5);
			if (ret == OK){
				video->cb(&frame);
				get = 1;
			}
		}
		if (!get){
            hloge("%s failed to hal_video_get_frame", __func__);
			hv_msleep(10);
		}
	}
}


uint32_t hal_video_openstream(HAL_SENSOR_IDX sensor_idx, hal_video_frame_callback cb, HAL_STREAM_CHANNEL stream_chn, const video_attr_st attr){
	struct list_head *pos, *n;
	list_for_each_safe(pos, n, &s_vlist){
		video_ins* video = list_entry(pos, video_ins, link);
        if (video->cb == cb) {
		   return 0;
        }
	}
    if (list_empty(&s_vlist)){ /* 第一次open 创建一个共用线程, 理论取流还是够, 避免用太多的线程了 */
	    hthread_create(hal_video_polling_task, NULL);
    }
	video_ins *video = (video_ins*)hv_malloc(sizeof(video_ins));
	if (!video){
		hloge("%s failed to hv_malloc", __func__);
		return -1;
	}
	video->cb     = cb;
	video->attr   = attr;
	list_add_tail(&video->link, &s_vlist);
	{
        /* to bind sensor and chn  */
        /* to start chn  */
        /* to start encode  */
	}
    
    
	
	return 0;
}

uint32_t hal_video_closestream(hal_video_frame_callback cb){
	struct list_head *pos, *n;
	list_for_each_safe(pos, n, &s_vlist){
		video_ins* video = list_entry(pos, video_ins, link);
        if (video->cb == cb) {
			//deinit chn
           list_del(pos);
		   hv_free(video);
		   return 0;
        }
	}
	return -1;
}

uint32_t hal_video_set_attr(HAL_SENSOR_IDX idx, HAL_STREAM_CHANNEL stream_chn, const video_attr_st * attr){
	//video_attr_st *a = &s_hal_video_st[idx][stream_chn].attr;

	/*
    uint32_t                width;             // resolution width, 0为不重复设置
    uint32_t                height;            // resolution height, 0为不重复设置
    uint32_t                bitrate;           // 码率: Kbit per second, 0为不重复设置
    uint32_t				fps;			   // 编码帧率
    uint32_t				gop;
	*/
	
}

