var addon = require('./liveMeidaClientPlugin.node');
var path = require('path');
var fs = require('fs');
var inited = false;

/**
 * 异步回调
 * 开始录制/推流
 */
addon.setRunCallback(function (msg) {
    console.log(msg);
});

/**
 * 定时检查
 */
setInterval(function() {
 	addon.onTimer();
}, 2000);

/**
 * 初始化
 */
exports.init_recorder = function() {
	//if(inited)
	//	return 1;
	
    var data = addon.initialize(false);
	if(data>=0)
		inited = true;
    return data;
}

/**
 * 注销/回收
 */
exports.un_init = function() {
    var data = addon.uninitialize();
    console.log(data);
	inited = false;
}

/**
 * 获取摄像头
 */
exports.get_cams = function() {
    var data = addon.getCameraCount();
    return data;
}

/**
 * 获取麦克风
 * @param index
 */
exports.get_mic = function(index) {
	var data = addon.getMicphoneNames(index);
	return data;
}

/**
 * 打开摄像头
 * @param index
 * @param width
 * @param height
 * @param fps
 */
exports.open_cam = function(index, width, height, fps) {
    var data = addon.openCamera(index, width, height, fps);
    return data;
}

/**
 * 打开麦克风
 * @param index
 */
exports.open_mic = function(mic_name) {
    var data;
	var l = addon.getMicphoneCount();
	for(var i=0;i<l;i++){
		console.log(mic_name,addon.getMicphoneNames(i));
		if(mic_name.indexOf(addon.getMicphoneNames(i))==0){
			data = addon.openMic(i);
			console.log(i,mic_name);
			return data;
		}
	}
	return '打开麦克风失败';
	var data = addon.openMic(0);
    return data;
}

/**
 * 开始录制
 * @param filename
 * @param handle
 * @param width
 * @param height
 * @param append
 * @quality 26 28 30 32 越小越清晰
 */
exports.start_record = function(filename, handle, width, height, fps, append, quality) {
    var dir = path.resolve(filename);
    console.log(dir,handle, width, height);
    exports.creat_path(path.dirname(dir));

    var data = addon.startRecordApp(dir, handle, width, height, fps, append, quality?quality:28);
    return data;
}

/**
 * 结束录制
 */
exports.stop_record = function() {
	var data = addon.stopRecordApp();
    return data;
}

/**
 * 开始推流
 * @param handle
 * @param rtmpurl
 * @param width
 * @param height
 * @quality 26 28 30 32 越小越清晰
 */
exports.start_publish = function(handle, rtmpurl, width, height, fps, type, quality) {
	//return true;
	var data = addon.publishStream(handle, rtmpurl, width, height, fps, type, quality?quality:28);
    return data;
}

/**
 * 结束推流
 */
exports.stop_publish = function() {
	//return true;
	var data = addon.stopPublishStream();
    return data;
}

/**
 * 获取窗口
 */
exports.get_windows = function() {
	var data = addon.enumWindowList()
    return data;
}

exports.creat_path = function(dir){
    console.log(dir);
    if(!fs.existsSync(dir)){
        return fs.mkdirSync(dir);
    }
    return true;
}

/**
 * 添加关键帧
 */
exports.add_keyframe = function(rtmpurl) {
	var data = addon.forceKeyFrame(rtmpurl);
	return data;
}