/* 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 display = exports;

var lcd;

function convert_lcd_type(type) {
  switch(type) {
  case '4.3inch':	return native.LCDTYPE['4_3INCH'];
  default:			return native.LCDTYPE['4_3INCH'];
  }
}

function convert_buffer_format(format) {
  switch(format) {
  case 'ycbcr422':	return native.BUFFERFORMAT.YCBCR422;
  case 'rgb565':	return native.BUFFERFORMAT.RGB565;
  case 'rgb888':	return native.BUFFERFORMAT.RGB888;
  case 'argb8888':	return native.BUFFERFORMAT.ARGB8888;
  case 'argb4444':	return native.BUFFERFORMAT.ARGB4444;
  default:			return native.BUFFERFORMAT.MAX;
  }
}

display.openLCD = function(config, callback) {
  if(!lcd) {
    lcd = new native({
      type: convert_lcd_type(config.type)
    }, function(err) {
      if(callback) {
        lcd.type = config.type;
        callback(err, lcd);
      }
    });
  } else {
    if(callback) {
      callback(new Error('LCD is already opened.'));
    }
  }
};


display.openLCDSync = function(config) {
  if(!lcd) {
    lcd = new native({
      type: convert_lcd_type(config.type)
    });
    lcd.type = config.type;
    return lcd;
  } else {
    throw new Error('LCD is already opened.');
  }
};

native.prototype.start = function(layer, buf, format, callback) {
  native.startImpl(this, layer, buf, convert_buffer_format(format), callback);
};

native.prototype.startSync = function(layer, buf, format) {
  native.startSyncImpl(this, layer, buf, convert_buffer_format(format));
};

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

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

