package com.castlabs.reactnative.errors;

import androidx.annotation.NonNull;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.WritableMap;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Provides convenient methods for rejecting the promise.
 */
public class Rejecter {
  private final Promise promise;

  public Rejecter(@NonNull Promise promise) {
    this.promise = promise;
  }

  /**
   * Rejects the promise with the given error.
   *
   * @param error the error
   */
  public void reject(@NonNull Exception error) {
    String errorString;

    if (error instanceof PrestoPlayError) {
      PrestoPlayError prestoPlayError = (PrestoPlayError) error;

      try {
        WritableMap json = prestoPlayError.toJson();
        errorString = json.toString();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    } else {

      // generic error handling
      JSONObject json = new JSONObject();
      try {
        json.put("code", ErrorCode.PLAYER_ERROR.value);
        json.put("severity", ErrorSeverity.RECOVERABLE.value);

        JSONObject data = new JSONObject();
        data.put("message", error.getMessage());

        json.put("metadata", data);
        errorString = json.toString();
      } catch (JSONException e) {
        throw new RuntimeException(e);
      }
    }

    promise.reject("PrestoPlayError", errorString);
  }
}
