/* Copyright 2017-present Renesas Electronics Corporation and other contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var video = exports;

var videoSource;

function convert_pixel_format(format) {
	switch(format) {
	case 'ycbcr422':	return native.PIXELFORMAT.YCBCR422;
	case 'rgb565':		return native.PIXELFORMAT.RGB565;
	case 'rgb888':		return native.PIXELFORMAT.RGB888;
	default:			return native.PIXELFORMAT.MAX;
	}
}

function convert_camera_type(type) {
	switch(type) {
	case 'ov7725':		return native.CAMERATYPE.OV7725;
	default:			return native.CAMERATYPE.OV7725;
	}
}

function convert_channel_num(channel) {
	switch(channel) {
	case 0:				return native.CHANNEL.CHANNEL_0;
	case 1:				return native.CHANNEL.CHANNEL_1;
	default:			return native.CHANNEL.MAX;
	}
}

function convert_signal_format(signal) {
	switch(signal) {
	case 'ntsc':		return native.SIGNALFORMAT.NTSC;
	case 'pal':			return native.SIGNALFORMAT.PAL;
	default:			return native.SIGNALFORMAT.NTSC;
	}
}

video.openCMOSCamera = function(config, callback) {
  if(!videoSource) {
    videoSource = new native({
      width: config.width,
      height: config.height,
      format: convert_pixel_format(config.format),
      type: convert_camera_type(config.type)
    }, native.DEVICETYPE.CMOSCAMERA, function(err) {
      if(callback) {
        videoSource.pixelFormat = config.format;
        videoSource.type = config.type;
        callback(err, videoSource);
      }
    });
  } else {
    if(callback) {
      callback(new Error('Camera is already opened.'));
    }
  }
};


video.openCMOSCameraSync = function(config) {
  if(!videoSource) {
    videoSource = new native({
      width: config.width,
      height: config.height,
      format: convert_pixel_format(config.format),
      type: convert_camera_type(config.type)
    }, native.DEVICETYPE.CMOSCAMERA);

    videoSource.pixelFormat = config.format;
    videoSource.type = config.type;
    return videoSource;
  } else {
    throw new Error('Camera is already opened.');
  }
};


native.prototype.close = function(callback) {
  native.closeImpl(this, function(err) {
    videoSource = null;
    if(callback) {
      callback(err);
    }
  });
};

native.prototype.closeSync = function() {
  native.closeSyncImpl(this);
  videoSource = null;
};
