/* 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 handle = new native({});

function convert_pixel_format(format) {
	switch(format) {
	case 'ycbcr422':	return handle.PIXELFORMAT.YCBCR422;
	case 'argb8888':	return handle.PIXELFORMAT.ARGB8888;
	case 'rgb565':		return handle.PIXELFORMAT.RGB565;
	default:			return handle.PIXELFORMAT.MAX;
	}
}

function Jpeg() {
}


Jpeg.prototype.encode = function(image, callback) {
  handle.encode({
    width: image.width,
    height: image.height,
    format: convert_pixel_format(image.format),
    bitmap: image.bitmap
  }, callback);
};


Jpeg.prototype.encodeSync = function(image) {
  return handle.encodeSync({
    width: image.width,
    height: image.height,
    format: convert_pixel_format(image.format),
    bitmap: image.bitmap
  });
};


Jpeg.prototype.decode = function(jpegData, config, callback) {
  handle.decode(jpegData, {
    width: config.width,
    height: config.height,
    format: convert_pixel_format(config.format),
    alpha: config.alpha
  }, function(err, bitmap) {
    if(callback) {
      var ret;
      if(!err) {
        ret = {
          width : config.width,
          height : config.height,
          format : config.format,
          bitmap : bitmap
        };
      }
      callback(err, ret);
    }
  });
};


Jpeg.prototype.decodeSync = function(jpegData, config) {
   var bitmap = handle.decodeSync(jpegData, {
    width: config.width,
    height: config.height,
    format: convert_pixel_format(config.format),
    alpha: config.alpha
  });
  var ret = {
    width : config.width,
    height : config.height,
    format : config.format,
    bitmap : bitmap
  };
  return ret;
};


module.exports = new Jpeg();
module.exports.Jpeg = Jpeg;
