#include "ISXMr.h"
#include "ExportCommand.h"

#include <chrono>
#include <future>
#include <thread>

#include "Logger.h"
#include "isxeq2/ExtensionTLOs.h"

AbilityInfo GetAbilityInfo(const int idx) {
    const auto ability = ExtensionTLOs::Me().Ability(idx);
    while (!ability.IsAbilityInfoAvailable()) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

    return ability.GetAbilityInfo();
}

void ExportCommand::Execute() {
    try {
        log << "Exporting abilities" << endl;
        const auto numAbilities = ExtensionTLOs::Me().NumAbilities();
        for (int i = 1; i <= numAbilities && !IsStopRequested(); ++i) {
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
            while (!ExtensionTLOs::Me().Ability(i).IsAbilityInfoAvailable() && !IsStopRequested()) {
                std::this_thread::sleep_for(std::chrono::milliseconds(200));
            }

            if (IsStopRequested()) {
                log << "Exporting abilities cancelled" << endl;
                return;
            }

            const auto abilityInfo = ExtensionTLOs::Me().Ability(i).GetAbilityInfo();
            log << "Exporting " << abilityInfo.Name() << "(" << i << "/" << numAbilities << ")" << endl;
        }
    } catch (const std::exception &e) {
        loge << "Error exporting abilities: " << e.what() << endl;
    } catch (...) {
        loge << "Unknown error exporting abilities" << endl;
    }

    log << "Exporting abilities finished" << endl;
}
