#include "SpallaCoreModule.h"

#include <chrono>
#include <utility>

namespace facebook::react {

namespace {

spalla::SwitchTrigger parseTrigger(const std::string& trigger) {
  if (trigger == "buffer") {
    return spalla::SwitchTrigger::Buffer;
  }
  if (trigger == "stall") {
    return spalla::SwitchTrigger::Stall;
  }
  return spalla::SwitchTrigger::Error;
}

}  // namespace

SpallaCoreModule::SpallaCoreModule(std::shared_ptr<CallInvoker> jsInvoker)
    : NativeSpallaCoreCxxSpec(jsInvoker),
      jsInvoker_(std::move(jsInvoker)),
      timerState_(std::make_shared<TimerState>()) {
  auto state = timerState_;
  state->tick = [this] { tickTelemetries(); };
  telemetryTimer_ = std::thread([this, state] {
    std::unique_lock<std::mutex> lock(state->mutex);
    while (!state->stop) {
      if (state->condition.wait_for(lock, std::chrono::seconds(1),
                                    [&state] { return state->stop; })) {
        break;
      }
      if (!telemetryPlaying_.load()) {
        continue;
      }
      lock.unlock();
      jsInvoker_->invokeAsync([state](jsi::Runtime&) {
        std::function<void()> tick;
        {
          std::lock_guard<std::mutex> stateLock(state->mutex);
          tick = state->tick;
        }
        if (tick) {
          tick();
        }
      });
      lock.lock();
    }
  });
}

SpallaCoreModule::~SpallaCoreModule() {
  {
    std::lock_guard<std::mutex> lock(timerState_->mutex);
    timerState_->stop = true;
    timerState_->tick = {};
  }
  timerState_->condition.notify_all();
  if (telemetryTimer_.joinable()) {
    telemetryTimer_.join();
  }
}

void SpallaCoreModule::setPostHandler(
    jsi::Runtime& rt, AsyncCallback<double, std::string, std::string> handler) {
  postHandler_ =
      std::make_shared<AsyncCallback<double, std::string, std::string>>(std::move(handler));
}

void SpallaCoreModule::completePost(jsi::Runtime& rt, double requestId, bool ok) {
  auto it = pendingPosts_.find(requestId);
  if (it == pendingPosts_.end()) {
    return;
  }
  auto done = std::move(it->second);
  pendingPosts_.erase(it);
  done(ok);
}

std::string SpallaCoreModule::getLocalizador(jsi::Runtime& rt) {
  return spalla::getLocalizador();
}

spalla::PostCallback SpallaCoreModule::makePostCallback() {
  return [this](const std::string& url, const std::string& bodyJson, spalla::PostDone done) {
    if (!postHandler_) {
      done(false);
      return;
    }
    const double requestId = nextRequestId_++;
    pendingPosts_.emplace(requestId, std::move(done));
    postHandler_->call(requestId, url, bodyJson);
  };
}

double SpallaCoreModule::telemetryCreate(jsi::Runtime& rt, std::string contentId,
                                         std::string uid, std::string osFamily,
                                         std::string osVersion) {
  spalla::TelemetryOptions options;
  options.contentId = std::move(contentId);
  options.uid = std::move(uid);
  options.engine = "spalla-rn";
  options.osFamily = std::move(osFamily);
  options.osVersion = std::move(osVersion);
  options.post = makePostCallback();
  const int32_t handle = nextHandle_++;
  telemetries_.emplace(handle, std::make_unique<spalla::Telemetry>(std::move(options)));
  return handle;
}

void SpallaCoreModule::tickTelemetries() {
  for (auto& entry : telemetries_) {
    entry.second->tick();
  }
}

void SpallaCoreModule::setTelemetryPlaying(double handle, bool playing) {
  const int32_t sessionHandle = static_cast<int32_t>(handle);
  if (playing) {
    playingTelemetries_.insert(sessionHandle);
  } else {
    playingTelemetries_.erase(sessionHandle);
  }
  telemetryPlaying_.store(!playingTelemetries_.empty());
}

spalla::Telemetry* SpallaCoreModule::telemetry(double handle) {
  auto it = telemetries_.find(static_cast<int32_t>(handle));
  return it == telemetries_.end() ? nullptr : it->second.get();
}

spalla::CdnFailover* SpallaCoreModule::failover(double handle) {
  auto it = failovers_.find(static_cast<int32_t>(handle));
  return it == failovers_.end() ? nullptr : it->second.get();
}

void SpallaCoreModule::telemetrySetConfig(jsi::Runtime& rt, double handle,
                                          std::string configJson) {
  if (auto* session = telemetry(handle)) {
    session->setConfig(configJson);
  }
}

void SpallaCoreModule::telemetrySetData(jsi::Runtime& rt, double handle,
                                        std::string dataJson) {
  if (auto* session = telemetry(handle)) {
    session->setData(dataJson);
  }
}

void SpallaCoreModule::telemetrySetCdn(jsi::Runtime& rt, double handle, std::string name) {
  if (auto* session = telemetry(handle)) {
    session->setCdn(name);
  }
}

void SpallaCoreModule::telemetryEvent(jsi::Runtime& rt, double handle, std::string tipo,
                                      std::string extrasJson) {
  if (auto* session = telemetry(handle)) {
    extrasJson.empty() ? session->event(tipo) : session->event(tipo, extrasJson);
  }
}

void SpallaCoreModule::telemetryKeyEvent(jsi::Runtime& rt, double handle, std::string tipo,
                                         std::string extrasJson) {
  if (auto* session = telemetry(handle)) {
    session->keyEvent(tipo, extrasJson);
  }
}

void SpallaCoreModule::telemetryErrorEvent(jsi::Runtime& rt, double handle, std::string tipo,
                                           std::string code, std::string message) {
  if (auto* session = telemetry(handle)) {
    session->errorEvent(tipo, code, message);
  }
}

void SpallaCoreModule::telemetryOnPlay(jsi::Runtime& rt, double handle) {
  if (auto* session = telemetry(handle)) {
    setTelemetryPlaying(handle, true);
    session->onPlay();
  }
}

void SpallaCoreModule::telemetryOnPause(jsi::Runtime& rt, double handle) {
  if (auto* session = telemetry(handle)) {
    session->onPause();
    setTelemetryPlaying(handle, false);
  }
}

void SpallaCoreModule::telemetryOnPlaying(jsi::Runtime& rt, double handle) {
  if (auto* session = telemetry(handle)) {
    setTelemetryPlaying(handle, true);
    session->onPlaying();
  }
}

void SpallaCoreModule::telemetryOnSeek(jsi::Runtime& rt, double handle) {
  if (auto* session = telemetry(handle)) {
    session->onSeek();
  }
}

void SpallaCoreModule::telemetryOnEnded(jsi::Runtime& rt, double handle) {
  if (auto* session = telemetry(handle)) {
    session->onEnded();
    setTelemetryPlaying(handle, false);
  }
}

void SpallaCoreModule::telemetryOnTimeUpdate(jsi::Runtime& rt, double handle, double timeS) {
  if (auto* session = telemetry(handle)) {
    session->onTimeUpdate(timeS);
  }
}

void SpallaCoreModule::telemetryEnd(jsi::Runtime& rt, double handle) {
  if (auto* session = telemetry(handle)) {
    session->end();
    setTelemetryPlaying(handle, false);
  }
}

void SpallaCoreModule::telemetryFlush(jsi::Runtime& rt, double handle) {
  if (auto* session = telemetry(handle)) {
    session->flush();
  }
}

void SpallaCoreModule::telemetryDestroy(jsi::Runtime& rt, double handle) {
  telemetries_.erase(static_cast<int32_t>(handle));
  setTelemetryPlaying(handle, false);
}

double SpallaCoreModule::failoverCreate(jsi::Runtime& rt, double nowMs) {
  const int32_t handle = nextHandle_++;
  failovers_.emplace(handle, std::make_unique<spalla::CdnFailover>(nowMs));
  return handle;
}

void SpallaCoreModule::failoverConfigure(jsi::Runtime& rt, double handle, double cdnCount,
                                         bool isVod, double stallLimitMs, double bufferMinS,
                                         double qualityRestoreMs) {
  if (auto* controller = failover(handle)) {
    controller->configure(static_cast<int>(cdnCount), isVod,
                          {stallLimitMs, bufferMinS, qualityRestoreMs});
  }
}

bool SpallaCoreModule::failoverIsEnabled(jsi::Runtime& rt, double handle) {
  auto* controller = failover(handle);
  return controller != nullptr && controller->isEnabled();
}

bool SpallaCoreModule::failoverHasGivenUp(jsi::Runtime& rt, double handle) {
  auto* controller = failover(handle);
  return controller != nullptr && controller->hasGivenUp();
}

double SpallaCoreModule::failoverErrorSwitchDelayMs(jsi::Runtime& rt, double handle,
                                                    double nowMs) {
  auto* controller = failover(handle);
  return controller != nullptr ? controller->errorSwitchDelayMs(nowMs) : 0;
}

bool SpallaCoreModule::failoverCanSwitchForBuffer(jsi::Runtime& rt, double handle,
                                                  double nowMs) {
  auto* controller = failover(handle);
  return controller != nullptr && controller->canSwitchForBuffer(nowMs);
}

void SpallaCoreModule::failoverRecordSwitch(jsi::Runtime& rt, double handle,
                                            std::string trigger, double nowMs) {
  if (auto* controller = failover(handle)) {
    controller->recordSwitch(parseTrigger(trigger), nowMs);
  }
}

void SpallaCoreModule::failoverRecordRecovery(jsi::Runtime& rt, double handle) {
  if (auto* controller = failover(handle)) {
    controller->recordRecovery();
  }
}

std::string SpallaCoreModule::failoverGetCountersJson(jsi::Runtime& rt, double handle) {
  auto* controller = failover(handle);
  return controller != nullptr ? controller->countersJson()
                               : R"({"trocas_por_erro":0,"trocas_por_buffer":0,"trocas_por_tempo":0})";
}

double SpallaCoreModule::failoverStallLimitMs(jsi::Runtime& rt, double handle) {
  auto* controller = failover(handle);
  return controller != nullptr ? controller->stallLimitMs() : 9000;
}

double SpallaCoreModule::failoverBufferMinS(jsi::Runtime& rt, double handle) {
  auto* controller = failover(handle);
  return controller != nullptr ? controller->bufferMinS() : 3;
}

double SpallaCoreModule::failoverQualityRestoreMs(jsi::Runtime& rt, double handle) {
  auto* controller = failover(handle);
  return controller != nullptr ? controller->qualityRestoreMs() : 45000;
}

void SpallaCoreModule::failoverDestroy(jsi::Runtime& rt, double handle) {
  failovers_.erase(static_cast<int32_t>(handle));
}

}  // namespace facebook::react
