//
// Created by Dan Crosby on 11/4/21.
//

#include "src/main/cpp/net/eagle0/shardok/library/action_result_applier/UnitHelpers.hpp"

namespace shardok::fb {

using namespace net::eagle0::shardok::storage::fb;

auto ApplyUnit(
        Unit* toUnit,
        const Unit* fromUnit,
        const net::eagle0::shardok::storage::fb::UnitStatus status) -> bool {
    float totalSpentVigor = 0.0f;

    if (toUnit->has_attached_hero()) {
        const float vigorDelta =
                fromUnit->attached_hero().vigor() - toUnit->attached_hero().vigor();
        if (vigorDelta < 0) {
            // Spent vigor cannot exceed starting vigor
            totalSpentVigor = std::min(
                    toUnit->attached_hero().spent_vigor() - vigorDelta,
                    toUnit->attached_hero().starting_vigor());
        } else {
            totalSpentVigor = toUnit->attached_hero().spent_vigor();
        }
    }

    memcpy(toUnit, fromUnit, sizeof(Unit));
    toUnit->mutate_status(status);

    if (toUnit->has_attached_hero()) {
        toUnit->mutable_attached_hero().mutate_spent_vigor(totalSpentVigor);
    }

    return true;
}

}  // namespace shardok::fb
