#ifndef TILEMAP_H
#define TILEMAP_H

#include <iostream>
#include <fstream>
#include <sstream>
#include "rapidjson/document.h"

using namespace rapidjson;

struct TileMap {
    int compressionlevel;
    int height;
    bool infinite;
    std::vector<std::vector<int>> layers;

    int parseTilemap(std::string path) {
        // Step 1: Read the JSON file into a string
        std::ifstream file(path);
        if (!file) {
            std::cerr << "Error opening file!" << std::endl;
            return 1;
        }

        std::stringstream buffer;
        buffer << file.rdbuf();
        std::string jsonData = buffer.str();

        // Step 2: Parse the JSON string
        Document document;
        document.Parse(jsonData.c_str());

        // Step 3: Check if parsing was successful
        if (document.HasParseError()) {
            std::cerr << "Error parsing JSON!" << std::endl;
            return 1;
        }

        // Step 4: Access JSON fields
        if (document.HasMember("compressionlevel") && document["compressionlevel"].IsInt()) {
            compressionlevel = document["compressionlevel"].GetInt();
        }

        if (document.HasMember("height") && document["height"].IsInt()) {
            height = document["height"].GetInt();
        }

        if (document.HasMember("infinite") && document["infinite"].IsBool()) {
            infinite = (document["infinite"].GetBool() ? "true" : "false");
        }

        // Step 5: Accessing the layers and data
        if (document.HasMember("layers") && document["layers"].IsArray()) {
            const Value& layersDoc = document["layers"];
            std::cout << "Number of layers: " << layersDoc.Size() << std::endl;
            layers.reserve(layersDoc.Size());
            
            for (SizeType i = 0; i < layersDoc.Size(); i++) {
                if (layersDoc[i].HasMember("data") && layersDoc[i]["data"].IsArray()) {
                    const Value& data = layersDoc[i]["data"];
                    std::vector<int> layer_in;
                    layer_in.reserve(data.Size());
                    
                    for (SizeType j = 0; j < data.Size(); j++) {
                        layer_in.emplace_back(data[j].GetInt());
                    }
                    layers.emplace_back(layer_in);
                }
            }
        }
        
        std::cout << "size:" << layers[0].size() << std::endl;
        

        return 0;
    }
};

#endif
