#include "olcPGE_Sprite.h"
#include "olcPGE_ResourcePack.h"
#include <iostream>
#include <string>

void PrintUsage() {
    std::cout << "Usage: packer --list PACK_FILE"            << std::endl;
    std::cout << "       packer --add PACK_FILE FILE"        << std::endl;
    std::cout << "       packer --remove PACK_FILE FILE"     << std::endl;
    std::cout << "       packer --convert PNG_FILE SPR_FILE" << std::endl;
}

void ListEntries(olc::ResourcePack& pack) {
    auto entries = pack.GetEntries();
    std::cout << "Total entries: " << entries.size() << std::endl;
    for (auto entry: entries) {
        std::cout << entry << std::endl;
    }
}

int main(int argc, char *argv[])
{
    std::string packFile;
    std::string action;

    if (argc < 3) {
        PrintUsage();
        return -1;
    }

    action = argv[1];
    packFile = argv[2];

    olc::ResourcePack pack;
    if (action != "--convert") {
        pack.LoadPack(packFile);
    }

    if (action == "--list") {
        ListEntries(pack);
    } else if (action == "--add" || action == "--remove") {
        if (argc < 4) {
            PrintUsage();
            return -1;
        }
        for (int i = 3; i < argc; i++) {
            std::string fileName = argv[i];
            if (action == "--add") {
                if (!pack.AddToPack(fileName)) {
                    std::cerr << "Could not open file " << fileName << std::endl;
                    return -3;
                }
                std::cout << "+ " << fileName << std::endl;
            } else if (action == "--remove") {
                if (!pack.RemoveFromPack(fileName)) {
                    std::cerr << "Could not open file " << fileName << std::endl;
                    return -3;
                }
                std::cout << "- " << fileName << std::endl;
            }
        }
        std::cout << std::endl;
        ListEntries(pack);
    } else if (action == "--convert") {
        if (argc < 4) {
            PrintUsage();
            return -1;
        }
        olc::Sprite sprite;
        if (sprite.LoadFromFile(packFile) != olc::OK) {
            std::cerr << "Not valid PNG file " << packFile << std::endl;
            return -4;
        }
        std::string sprFile = argv[3];
        if (!sprite.SaveToPGESprFile(sprFile)) {
            std::cerr << "Could not save file " << sprFile << std::endl;
            return -3;
        }
        return 0;
    } else {
        PrintUsage();
        return -1;
    }

    if (!pack.SavePack(packFile)) {
        std::cerr << "Could not save file " << packFile << std::endl;
    }

    return 0;
}