//
//  BecomeOutlawCommand.cpp
//  eagle0
//
//  Created by Dan Crosby on 2021/06/13.
//  Copyright © 2021 none. All rights reserved.
//

#include "BecomeOutlawCommand.hpp"

#include <utility>

#include "src/main/cpp/net/eagle0/shardok/library/PercentileRollOdds.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/util/ActionResultFlatbufferHelpers.hpp"

namespace shardok {
auto BecomeOutlawCommand::InternalExecute(
        const GameStateW& currentState,
        const std::shared_ptr<RandomGenerator>& generator) const -> vector<ActionResult> {
    const auto roll = generator->Percentile();
    return ExecuteWithRoll(currentState, roll);
}

[[nodiscard]] auto BecomeOutlawCommand::ExecuteWithRoll(
        const GameStateW& currentState,
        const double roll) const -> vector<ActionResult> {
    ActionResult result{};
    result.mutable_player()->set_value(GetPlayerId());
    result.mutable_actor()->set_value(fleeingUnitId);
    net::eagle0::shardok::storage::ResolvedUnit* resolvedUnit = result.add_resolved_units();
    AddUnitToResolved(*resolvedUnit, *currentState->units()->Get(fleeingUnitId));

    if (PercentileRollSucceeds(successOdds, roll)) {
        result.set_type(net::eagle0::shardok::common::ActionType::BECAME_OUTLAW);
        resolvedUnit->set_status(
                net::eagle0::shardok::storage::ResolvedUnit_UnitStatus_OUTLAWED_UNIT);
    } else {
        result.set_type(net::eagle0::shardok::common::ActionType::CAPTURED_WHILE_FLEEING);
        resolvedUnit->set_status(
                net::eagle0::shardok::storage::ResolvedUnit_UnitStatus_CAPTURED_UNIT);
    }

    return {result};
}

BecomeOutlawCommand::BecomeOutlawCommand(
        const ActionCost& cost,
        const PlayerId playerId,
        const UnitId fleeingUnitId,
        PercentileRollOdds odds)
    : ShardokCommand(playerId),
      cost(cost),
      fleeingUnitId(fleeingUnitId),
      successOdds(std::move(odds)) {}

auto BecomeOutlawCommand::GetCommandProto() const -> CommandProto {
    CommandProto proto;

    proto.set_player(GetPlayerId());
    proto.set_type(net::eagle0::shardok::common::BECOME_OUTLAW_COMMAND);
    proto.mutable_actor()->set_value(fleeingUnitId);

    return proto;
}
}  // namespace shardok
