//
// Created by Dan Crosby on 5/31/20.
//

#include "ControlCommand.hpp"

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

namespace shardok {

using net::eagle0::shardok::common::ActionType;

auto ControlCommand::InternalExecute(
        const GameStateW& currentState,
        const std::shared_ptr<RandomGenerator>& generator) const -> vector<ActionResult> {
    const Unit* actor = currentState->units()->Get(actorId);
    if (!actor->has_attached_hero() ||
        actor->attached_hero().control_info().controlled_unit_id() == -1) {
        throw ShardokInternalErrorException(
                "A unit without a commanded unit attempting control action");
    }

    auto actorAfter = *actor;
    actorAfter.mutate_remaining_action_points(0);

    actorAfter.mutable_attached_hero().mutable_control_info().mutate_controlled_this_round(true);

    ActionResult result{};
    result.set_type(ActionType::CONTROLLED);
    result.mutable_player()->set_value(GetPlayerId());
    result.mutable_actor()->set_value(actorId);
    AddChangedUnit(result, actorAfter);

    return {result};
}

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

    proto.set_type(net::eagle0::shardok::common::CONTROL_COMMAND);
    proto.mutable_actor()->set_value(actorId);
    proto.mutable_target_unit()->set_value(targetId);

    return proto;
}

}  // namespace shardok
