#include <yandex/maps/wiki/validator/objects/condition.h>

#include "object_init_helpers.h"
#include <maps/wikimap/mapspro/libs/validator/common/exception.h>
#include <maps/wikimap/mapspro/libs/validator/common/magic_strings.h>

namespace maps::wiki::validator {

Condition::Condition(
            TId id,
            const AttrMap& attributes,
            const Relations& /* masters */,
            const Relations& slaves)
        : id_(id)
        , type_(
                extractAttrBySuffix<common::ConditionType>(
                        attributes, COND_TYPE_ATTR_SUFFIX, IsMandatory::Yes,
                        "bad-cond-type", id))
        , accessId_(
                extractAttrBySuffix<common::AccessId>(
                        attributes, ACCESS_ID_ATTR_SUFFIX, IsMandatory::No,
                        "bad-access-id", id))
        , viaJunction_(
                extractRelation(
                        slaves, VIA_JUNCTION_ROLE, IsMandatory::Yes,
                        "bad-via-junction-relation", id))
        , fromRoadElement_(
                extractRelation(
                        slaves, FROM_RD_EL_ROLE, IsMandatory::Yes,
                        "bad-from-element-relation", id))
        , schedules_(extractRelations(slaves, APPLIED_TO_ROLE))
        , vehicleRestrictionParameters_(readVehicleRestrictionParameters(attributes, id))
{
    requireOnObjectLoad(common::isValid(type_), "bad-cond-type", id);
    requireOnObjectLoad(common::isValid(accessId_), "bad-access-id", id);

    for (const auto& relation : slaves) {
        if (relation.role == TO_RD_EL_ROLE) {
            if (!relation.seqNum) {
                throw InvalidRelationsException(
                    "bad-cond-relation", id,
                    {relation.other});
            }
            toRoadElements_.emplace_back(*relation.seqNum, relation.other);
        }
    }
    std::sort(toRoadElements_.begin(), toRoadElements_.end());
}

} // namespace maps::wiki::validator
