#include "mode_controls.h"

namespace NModCookiePolicy {
    TModeControls::TPolicyMode::TPolicyMode(const TPolicyModeCfg& cfg) noexcept
        : Mode(cfg.mode())
    {
        for (auto&& dm : cfg.domain_modes()) {
            DomainModes.emplace_back(TPolicyDomainMode{
                .Mode=dm.mode(),
                .DomainFilter=TDomainFilter(dm.domain_filter())
            });
        }
    }

    TMaybe<EPolicyMode> TModeControls::TPolicyMode::GetMode(const TDomainInfo& domainInfo) const noexcept {
        for (auto&& domainMode : DomainModes) {
            const auto& f = domainMode.DomainFilter;
            if (f.Included(domainInfo) && !f.Excluded(domainInfo)) {
                return domainMode.Mode;
            }
        }
        return Mode;
    }

    TModeControls::TModeControls(const TModeControlsCfg& cfg) noexcept
        : ParserMode_(cfg.parser_mode())
    {
        for (auto&& pm : cfg.policy_modes()) {
            PolicyModes_.emplace(pm.first, pm.second);
        }
    }

    TMaybe<EPolicyMode> TModeControls::PolicyMode(TStringBuf name, const TDomainInfo& domainInfo) const noexcept {
        if (auto it = PolicyModes_.find(name); it != PolicyModes_.end()) {
            return it->second.GetMode(domainInfo);
        }
        return Nothing();
    }

    TMaybe<EPolicyMode> TModeControls::ParserMode(const TDomainInfo& domainInfo) const noexcept {
        return ParserMode_.GetMode(domainInfo);
    }
}
