#include "video_source.h"

video_source::video_source(TFT_eSPI *tft, AudioBuffer &audioBuffer,
                           String frame_url)
    : tft(tft), audioBuffer(audioBuffer), frame_url(frame_url) {
  zt = new zlib_turbo();
  pCompressed = nullptr;
  pCompressedSize = 0;
  pUncompressed = nullptr;
  pUncompressedSize = 0;
  l = 0;
  lt = 0;

  fps = new FPS();
  http = new HTTPClient();

  // Initialize the HTTP connection once
  http->setReuse(true);   // Enable connection reuse
  http->begin(frame_url); // Initialize the connection
}

video_source::~video_source() {
  delete zt;
  if (pCompressed != nullptr) {
    free(pCompressed);
  }
  if (pUncompressed != nullptr) {
    free(pUncompressed);
  }

  http->end(); // Properly close the HTTP connection
  delete http;
}

void video_source::grab_frame() {
  // unsigned long startTime, stepTime;
  static unsigned long startTime;

  // Step 1: Ensure WiFi is connected
  // startTime = micros();
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("WiFi not connected");
    return;
  }
  // stepTime = micros() - startTime;
  // Serial.printf("Step 1 (Check WiFi): %lu us\n", stepTime);

  // static uint64_t audioFrame = 0;

  startTime = millis();

  while (true) {
    if (frame_ready == false) {
      // Step 2: Send GET request

      //? Set Request header
      // http->addHeader("X-Audio-Frame", String(audioFrame++));
      //? Set response headers to parse
      const char *headerkeys[] = {"X-Video-Length"};
      const size_t headerkeyscount = sizeof(headerkeys) / sizeof(headerkeys[0]);
      http->collectHeaders(headerkeys, headerkeyscount);

      int httpResponseCode = http->GET();
      // stepTime = micros() - startTime;
      // Serial.printf("Step 2 (Send GET request): %lu us\n", stepTime);

      if (httpResponseCode == 200) {
        // Step 3: Get the size of the payload
        // startTime = micros();
        int contentLength = http->getSize();
        if (contentLength <= 0) {
          Serial.println("Content-Length not found");
          continue;
        }

        // stepTime = micros() - startTime;
        // Serial.printf("Step 3 (Get payload size): %lu us\n", stepTime);

        // Step 4: Allocate or resize memory for compressed data
        // startTime = micros();
        if (pDL == nullptr) {
          pDL = (uint8_t *)heap_caps_malloc(contentLength, MALLOC_CAP_INTERNAL);
          pDLSize = contentLength;
        } else if (pDLSize < (size_t)contentLength) {
          uint8_t *newBuffer = (uint8_t *)realloc(pDL, contentLength);
          if (!newBuffer) {
            Serial.println("Failed to reallocate memory for DL data");
            continue;
          }
          pDL = newBuffer;
          pDLSize = contentLength;
        }
        // stepTime = micros() - startTime;
        // Serial.printf("Step 4 (Allocate/resize memory): %lu us\n", stepTime);

        // Step 5: Read data from the stream
        // startTime = micros();
        WiFiClient *stream = http->getStreamPtr();
        int bytesRead = 0;

        while (http->connected() && (bytesRead < contentLength)) {
          // Check how many bytes are available in the stream
          int bytesAvailable = stream->available();
          if (bytesAvailable > 0) {
            // Calculate the number of bytes to read in this iteration
            int bytesToRead = min(bytesAvailable, contentLength - bytesRead);

            // Read directly into the pDL buffer at the correct offset
            int bytesReadNow = stream->read(pDL + bytesRead, bytesToRead);

            // Update the total number of bytes read
            bytesRead += bytesReadNow;
          }
        }

        if (bytesRead != contentLength) {
          Serial.printf("Read %d bytes instead of %d\n", bytesRead,
                        contentLength);
          Serial.println("Failed to read the entire payload");
          continue;
        }

        // Get video and audio part length
        String pDLVideoSizeStr = http->header("X-Video-Length");
        int pDLVideoSize = 0;
        if (pDLVideoSizeStr == "") {
          Serial.println("Video size not found");
          continue;
        } else {
          pDLVideoSize = pDLVideoSizeStr.toInt();
        }
        int pDLAudioSize = contentLength - pDLVideoSize;
        // Serial.printf("Video size: %d, Audio size: %d\n", pDLVideoSize,
        // pDLAudioSize);

        // Allocate memory for compressed video data
        if (pCompressed == nullptr) {
          // pCompressed = (uint8_t *)heap_caps_aligned_alloc(2, pDLSize,
          // MALLOC_CAP_INTERNAL);
          pCompressed =
              (uint8_t *)heap_caps_malloc(pDLVideoSize, MALLOC_CAP_INTERNAL);
          pCompressedSize = pDLVideoSize;
        } else if (pCompressedSize < (size_t)pDLVideoSize) {
          uint8_t *newBuffer = (uint8_t *)realloc(pCompressed, pDLVideoSize);
          if (!newBuffer) {
            Serial.println("Failed to reallocate memory for compressed data");
            continue;
          }
          pCompressed = newBuffer;
          pCompressedSize = pDLVideoSize;
        }
        // Copy compressed video data to buffer for decompression
        memcpy(pCompressed, pDL, pDLVideoSize);
        frame_ready = true;

        startTime = millis() - startTime;
        // Serial.printf("Frame ready in %lu ms\n", startTime);
        if (int(startTime) < (1000 / 20)) {
          vTaskDelay(max((1000 / 20) - int(startTime), 0) /
                     portTICK_PERIOD_MS);
        }

        // Pass audio data to audio buffer
        audioBuffer.updateBuffer(pDL + pDLVideoSize, pDLAudioSize);

        startTime = millis();

        // stepTime = micros() - startTime;
        // Serial.printf("Step 5 (Read data from stream): %lu us\n", stepTime);
        // return 0;
        // vTaskDelay(20 / portTICK_PERIOD_MS);

      } else {
        Serial.printf("Error on HTTP request: %s\n",
                      http->errorToString(httpResponseCode).c_str());

        tft->fillScreen(TFT_BLUE);
        tft->setCursor(0, 0, 4);
        tft->printf("Error on HTTP request: %s",
                    http->errorToString(httpResponseCode).c_str());

        vTaskDelay(10 / portTICK_PERIOD_MS);
        continue;
      }
    } else {
      vTaskDelay(1 / portTICK_PERIOD_MS);
    }
  }
}

void video_source::decode_and_display() {
  // unsigned long startTime, stepTime;

  while (true) {

    if (frame_ready) {

      frame_ready = false;
      // Step 6: Decompress the data

      int pUncompressedSize = TFT_WIDTH * TFT_HEIGHT * sizeof(uint16_t);
      if (pUncompressed == nullptr) {
        pUncompressed =
            (uint8_t *)heap_caps_malloc(pUncompressedSize, MALLOC_CAP_INTERNAL);
      }
      zt->inflate_init(pUncompressed, pUncompressedSize);

      int rc = zt->inflate(pCompressed, pCompressedSize + 8);

      if (rc == ZT_SUCCESS) {

        // Step 7: Draw the image
        // startTime = micros();
        tft->pushImage(0, 0, TFT_WIDTH, TFT_HEIGHT, (uint16_t *)pUncompressed);
        // stepTime = micros() - startTime;
        // Serial.printf("Step 7 (Draw image): %lu us\n", stepTime);

        fps->frame();
        // Serial.printf("FPS: %.2f\n", fps->getFPS());
        tft->setCursor(0, 0, 4);
        tft->printf("FPS: %.2f", fps->getFPS());

        // Print free heap memory to Serial
        // Serial.printf("Free heap memory: %u bytes\n",
        // heap_caps_get_free_size(MALLOC_CAP_INTERNAL));

      } else {
        Serial.printf("Decompression failed: ");

        switch (rc) {
        case 1:
          Serial.printf("ZT_HEADER_ERROR\n");
          break;
        case 2:
          Serial.printf("ZT_DECODE_ERROR\n");
          break;
        case 3:
          Serial.printf("ZT_OUTPUT_INSUFFICIENT\n");
          break;
        case 4:
          Serial.printf("ZT_DATA_ERROR\n");
          break;
        case 5:
          Serial.printf("ZT_INVALID_PARAMETER\n");
          break;
        default:
          Serial.printf("UNKNOWN_ERROR\n");
          break;
        }
        vTaskDelay(1 / portTICK_PERIOD_MS);
        continue;
      }

    } else {
      vTaskDelay(1 / portTICK_PERIOD_MS);
    }
  }
}

void video_source::start_tasks() {
  // Create the grab task
  // xTaskCreate(grab_task, "GrabTask", 8192, this, 1, NULL);
  xTaskCreatePinnedToCore(grab_task, "GrabTask", 8192, this, 1, NULL,
                          GRAB_TASK_CORE);

  // Create the decode and display task
  // xTaskCreate(decode_task, "DecodeTask", 8192, this, 1, NULL);
  xTaskCreatePinnedToCore(decode_task, "DecodeTask", 8192, this, 1, NULL,
                          DECODE_TASK_CORE);
}

void video_source::grab_task(void *pvParameters) {
  video_source *vs = static_cast<video_source *>(pvParameters);
  vs->grab_frame();
}

void video_source::decode_task(void *pvParameters) {
  video_source *vs = static_cast<video_source *>(pvParameters);
  vs->decode_and_display();
}
