#include "ThorGlRenderer.hpp"

#include <thorvg.h>
#include <EGL/egl.h>
#include <GLES3/gl3.h>
#include <android/log.h>

using namespace tvg;

namespace {

bool ensureThorVGInit() {
  // Share the CPU renderer's worker-thread count so both engines agree (the
  // count is fixed at the first Initializer::init across the whole process).
  static const bool ok =
      (Initializer::init(thor::recommendedThreadCount()) == Result::Success);
  return ok;
}

// Build one shape's geometry + paint. (Kept separate from the CPU renderer's
// copy on purpose, so the shared SW path stays untouched.)
void applyShape(Shape* shape, const thor::ThorShapeDesc& d) {
  switch (d.type) {
    case thor::ThorShapeType::Rect:
      shape->appendRect(d.x, d.y, d.w, d.h, d.rx, d.ry);
      break;
    case thor::ThorShapeType::Circle:
      shape->appendCircle(d.cx, d.cy, d.radius, d.radius);
      break;
    case thor::ThorShapeType::Line:
      shape->moveTo(d.x1, d.y1);
      shape->lineTo(d.x2, d.y2);
      break;
    case thor::ThorShapeType::Polygon:
      if (d.points.size() >= 4) {
        shape->moveTo(d.points[0], d.points[1]);
        for (size_t i = 2; i + 1 < d.points.size(); i += 2) {
          shape->lineTo(d.points[i], d.points[i + 1]);
        }
        if (d.closed) shape->close();
      }
      break;
  }

  if (d.hasFill) {
    shape->fill((d.fillColor >> 16) & 0xFF, (d.fillColor >> 8) & 0xFF,
                d.fillColor & 0xFF, (d.fillColor >> 24) & 0xFF);
  } else {
    shape->fill(0, 0, 0, 0);
  }

  if (d.hasStroke && d.strokeWidth > 0.0f) {
    shape->strokeWidth(d.strokeWidth);
    shape->strokeFill((d.strokeColor >> 16) & 0xFF, (d.strokeColor >> 8) & 0xFF,
                      d.strokeColor & 0xFF, (d.strokeColor >> 24) & 0xFF);
    shape->strokeJoin(StrokeJoin::Round);
    shape->strokeCap(StrokeCap::Round);
  } else {
    shape->strokeWidth(0.0f); // clear any stroke retained from a previous frame
  }
}

} // namespace

namespace thor {

ThorGlRenderer::ThorGlRenderer() { ensureThorVGInit(); }

ThorGlRenderer::~ThorGlRenderer() {
  if (_canvas) delete static_cast<GlCanvas*>(_canvas);
}

bool ThorGlRenderer::resize(uint32_t width, uint32_t height) {
  if (!ensureThorVGInit() || width == 0 || height == 0) return false;

  auto* canvas = static_cast<GlCanvas*>(_canvas);
  if (canvas == nullptr) {
    canvas = GlCanvas::gen();
    _canvas = canvas;
    if (canvas == nullptr) return false;
  }

  EGLDisplay display = eglGetCurrentDisplay();
  EGLSurface surface = eglGetCurrentSurface(EGL_DRAW);
  EGLContext context = eglGetCurrentContext();
  if (context == EGL_NO_CONTEXT) {
    __android_log_print(ANDROID_LOG_ERROR, "ThorGl", "no current EGL context");
    return false;
  }

  // FBO 0 = the window's default framebuffer (GLSurfaceView renders to it).
  // ThorVG's GL canvas only accepts ABGR8888S (straight / un-premultiplied alpha).
  _targeted = canvas->target((void*)display, (void*)surface, (void*)context, 0,
                             width, height, ColorSpace::ABGR8888S) == Result::Success;
  __android_log_print(_targeted ? ANDROID_LOG_INFO : ANDROID_LOG_ERROR, "ThorGl",
                      "GPU(GL) target %s %ux%u", _targeted ? "OK" : "FAILED", width, height);
  return _targeted;
}

bool ThorGlRenderer::renderScene(const std::vector<ThorShapeDesc>& shapes) {
  auto* canvas = static_cast<GlCanvas*>(_canvas);
  if (canvas == nullptr || !_targeted) return false;

  // Retained-scene update (see ThorRenderer::renderScene): reuse pooled shapes
  // rather than gen()/remove() every frame.
  const size_t need = shapes.size();
  while (_pool.size() < need) {
    auto* s = Shape::gen();
    canvas->add(s);
    _pool.push_back(s);
  }
  while (_pool.size() > need) {
    canvas->remove(static_cast<Shape*>(_pool.back()));
    _pool.pop_back();
  }
  for (size_t i = 0; i < need; ++i) {
    auto* shape = static_cast<Shape*>(_pool[i]);
    shape->reset();
    applyShape(shape, shapes[i]);
  }

  const bool ok = (canvas->draw(true) == Result::Success);
  canvas->sync();
  return ok;
}

} // namespace thor
