#include <iostream>
#include <fstream>
#include <vector>
#include <cstdint>
#include "SWIDecoder.h"

WiResultImage DecodeImage(unsigned char* imageData, int size);

//void rotate90(const std::vector<uint8_t>& src, std::vector<uint8_t>& dst, int width, int height) {
//    dst.resize(src.size());
//    for (int y = 0; y < height; ++y) {
//        for (int x = 0; x < width; ++x) {
//            int srcIdx = y * width + x;
//            int dstIdx = (height - 1 - y) * width + (width - 1 - x);
//            dst[dstIdx] = src[srcIdx];
//        }
//    }
//}

int main(int argc, char* argv[]) {
    if (argc != 3) {
        std::cout << "Usage: decodephoto input.bin output.pgm" << std::endl;
        return 1;
    }

    std::ifstream in(argv[1], std::ios::binary);
    if (!in) {
        std::cerr << "Cannot open input file" << std::endl;
        return 2;
    }
    std::vector<unsigned char> inputData((std::istreambuf_iterator<char>(in)), {});
    in.close();

    // Decode image via SWI decoder
    WiResultImage result = DecodeImage(inputData.data(), static_cast<int>(inputData.size()));
    const int width = 200;
    const int height = 250;

    if (result.size > 0 && result.raw != nullptr) {

//        std::vector<uint8_t> rotated;
//        rotate90(std::vector<uint8_t>(result.raw, result.raw + (width*height)), rotated, width, height);


        std::ofstream out(argv[2], std::ios::binary);
        out << "P5\n" << width << " " << height << "\n255\n";
        out.write(reinterpret_cast<char*>(result.raw), result.size);
        out.close();

        std::cout << "Decoded (and rotated) image written to " << argv[2] << std::endl;
        return 0;
    } else {
        std::cerr << "Image decoding failed!" << std::endl;
        return 3;
    }
}
