package org.reactnative.camera.events;

import androidx.core.util.Pools;

import org.reactnative.camera.CameraViewManager;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.uimanager.events.Event;
import com.facebook.react.uimanager.events.RCTEventEmitter;

import java.util.Date;
import java.nio.ByteBuffer;
import android.util.Base64;

public class FrameEvent extends Event<FrameEvent> {
  private static final Pools.SynchronizedPool<FrameEvent> EVENTS_POOL = new Pools.SynchronizedPool<>(3);
  private FrameEvent() {}

  private String msg;
  private byte[] data;

  public static FrameEvent obtain(int viewTag, String msg, byte[] data) {
    FrameEvent event = EVENTS_POOL.acquire();
    if (event == null) {
      event = new FrameEvent();
    }
    event.init(viewTag, msg, data);
    return event;
  }

  private void init(
    int viewTag,
    String msg,
    byte[] data
) {
  super.init(viewTag);
  this.data = data;
  this.msg = msg;
}

private String convertToBase64() {
    return Base64.encodeToString(data, Base64.DEFAULT);
}

  @Override
  public short getCoalescingKey() {
    return 0;
  }

  @Override
  public String getEventName() {
    return CameraViewManager.Events.EVENT_FRAME_PREVIEW.toString();
  }

  @Override
  public void dispatch(RCTEventEmitter rctEventEmitter) {
    rctEventEmitter.receiveEvent(getViewTag(), getEventName(), serializeEventData());
  }

  private WritableMap serializeEventData() {
    WritableMap event = Arguments.createMap();
    //WritableArray data = Arguments.createArray();
    //event.putString("msg", String.valueOf(data.position()));
    if(data!=null){
      try{
        event.putString("data", convertToBase64());
      }catch(Exception e){
        event.putString("ERROR", e.toString());
      }
    }else{
      event.putString("msg", msg);
    }
    return event;
  }
}