'use strict';

require('../../../omggif/omggif.js');
var index = require('../../../gifwrap/src/index.js');
var omggif = require('../../../../_virtual/omggif.js');

const MIME_TYPE = "image/gif";
var gif = (() => ({
  mime: {
    [MIME_TYPE]: ["gif"]
  },
  constants: {
    MIME_GIF: MIME_TYPE
  },
  decoders: {
    [MIME_TYPE]: data => {
      const gifObj = new omggif.__exports.GifReader(data);
      const gifData = Buffer.alloc(gifObj.width * gifObj.height * 4);
      gifObj.decodeAndBlitFrameRGBA(0, gifData);
      return {
        data: gifData,
        width: gifObj.width,
        height: gifObj.height
      };
    }
  },
  encoders: {
    [MIME_TYPE]: data => {
      const bitmap = new index.src.BitmapImage(data.bitmap);
      index.src.GifUtil.quantizeDekker(bitmap, 256);
      const newFrame = new index.src.GifFrame(bitmap);
      const gifCodec = new index.src.GifCodec();
      return gifCodec.encodeGif([newFrame], {}).then(newGif => {
        return newGif.buffer;
      });
    }
  }
}));

module.exports = gif;
