// ~/workdir/poomer-discord-helloworld/src/ImageProcessor.cpp
#include "../include/ImageProcessor.h"
#include <fstream>
#include <cstdio>
#include <algorithm> // For std::swap
#include <cstring>   // For std::memcpy

// You MUST define the implementation macros here, in the .cpp file,
// and include the stb headers. This is a crucial step for single-header libraries.
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

ImageProcessor::ImageProcessor(dpp::cluster& bot) : m_bot(bot) {
    // Constructor initializes the member variable
}

void ImageProcessor::flip_image_horizontally(unsigned char* data, int width, int height, int channels) {
    // ... (your horizontal flip implementation from before)
    /*for (int y = 0; y < height; ++y) {
        unsigned char *left = data + y * width * channels;
        unsigned char *right = left + (width - 1) * channels;
        for (int x = 0; x < width / 2; ++x) {
            for (int c = 0; c < channels; ++c) {
                std::swap(left[(x * channels) + c], right[(0 * channels) + c]);
            }
            left += channels;
            right -= channels;
        }
    }*/
    for (int y = 0; y < height; ++y) {
        // Get pointers to the start of the current row
        unsigned char* row_start = data + y * width * channels;
        
        // Loop through half the row, swapping pixels from left and right
        for (int x = 0; x < width / 2; ++x) {
            // Calculate the pointers to the left and right pixels
            unsigned char* left_pixel = row_start + x * channels;
            unsigned char* right_pixel = row_start + (width - 1 - x) * channels;
            
            // Swap each channel of the pixels
            for (int c = 0; c < channels; ++c) {
                std::swap(left_pixel[c], right_pixel[c]);
            }
        }
    }
}

void ImageProcessor::flip_image_vertically(unsigned char* data, int width, int height, int channels) {
    // ... (your vertical flip implementation from before)
    int row_stride = width * channels;
    unsigned char* temp_row = new unsigned char [row_stride];
    for (int y = 0; y < height / 2; ++y) {
        unsigned char* top_row = data + y * row_stride;
        unsigned char* bottom_row = data + (height - 1 - y) * row_stride;
        std::memcpy(temp_row, top_row, row_stride);
        std::memcpy(top_row, bottom_row, row_stride);
        std::memcpy(bottom_row, temp_row, row_stride);
    }
    delete[] temp_row;
}

void ImageProcessor::process_attachment(const dpp::message_create_t& event, const dpp::attachment& attachment) {
    std::string local_filename = "temp_" + std::to_string(attachment.id) + "_" + attachment.filename;

    m_bot.request(attachment.url, dpp::http_method::m_get,
        [this, event, local_filename, attachment](const dpp::http_request_completion_t& completion) {
            if (completion.status < 400) {
                std::ofstream file(local_filename, std::ios::binary);
                if (file.is_open()) {
                    file.write(completion.body.c_str(), completion.body.length());
                    file.close();

                    int width, height, channels;
                    //unsigned char* image_data = stbi_load_from_memory(local_filename.c_str(), &width, &height, &channels, 0);
                    unsigned char* image_data = stbi_load_from_memory(
                        reinterpret_cast<const stbi_uc*>(completion.body.data()), 
                        completion.body.length(), 
                        &width, &height, &channels, 0
                    );
                    if (image_data) {
                        // Flip the image horizontally (you can choose which flip to apply)
                        m_bot.log(dpp::ll_info,"channels: " + std::to_string(channels));
                        flip_image_horizontally(image_data, width, height, channels);

                        // --- Save the flipped image to a new temporary file ---
                        std::string flipped_filename = "flipped_" + local_filename;
                        stbi_write_jpg(flipped_filename.c_str(), width, height, channels, image_data, 100); // Quality 100

                        // --- NEW CODE STARTS HERE ---
                        dpp::message msg;
                        
                        // Add the file to the message
                        msg.add_file(flipped_filename, dpp::utility::read_file(flipped_filename));

                        // Create an embed and reference the attached file
                        dpp::embed embed;
                        embed.set_title("Image Info");
                        embed.set_description("Dimensions: " + std::to_string(width) + "x" + std::to_string(height));
                        embed.set_image("attachment://" + flipped_filename); // Reference the file here
                        
                        // Add the embed to the message
                        msg.add_embed(embed);
                        msg.set_channel_id(1398043078559797310);
                        m_bot.message_create(msg);

                        msg.set_content("Here's your horizontally flipped image");
                        event.reply(msg);
                        // --- NEW CODE ENDS HERE ---
                        
                        stbi_image_free(image_data);
                        std::remove(local_filename.c_str());
                        std::remove(flipped_filename.c_str()); // Clean up the flipped file
                    } else {
                        std::cerr << "Error: Failed to load image with stb from " << local_filename << std::endl;
                    }
                    std::remove(local_filename.c_str());
                } else {
                    std::cerr << "Failed to open local file for writing: " << local_filename << std::endl;
                }
            } else {
                std::cerr << "Failed to download image from " << attachment.url << ". HTTP status code: " << completion.status << std::endl;
            }
        });
}