/*
 * Copyright 2020 Bloomberg Finance LP
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <gtest/gtest.h>

#include <string>

#include <buildboxcasd_expiringunorderedset.h>

using buildboxcasd::ExpiringUnorderedSet;
using buildboxcasd::SelfCleaningExpiringUnorderedSet;

TEST(ExpiringUnorderedSet, TestEmpty)
{
    ExpiringUnorderedSet<int> setOfInt(2);
    ASSERT_EQ(setOfInt.keySecondsToLive(), 2);
    ASSERT_EQ(setOfInt.capacity(), 0);

    ExpiringUnorderedSet<std::string> setOfString(5);
    ASSERT_EQ(setOfString.keySecondsToLive(), 5);
    ASSERT_EQ(setOfString.capacity(), 0);
}

TEST(ExpiringUnorderedSet, TestInsert)
{
    ExpiringUnorderedSet<std::string> s(60);
    const auto key = "key";
    ASSERT_FALSE(s.contains(key));

    ASSERT_TRUE(s.insert(key));
    ASSERT_TRUE(s.contains(key));

    ASSERT_FALSE(s.insert(key));
}

TEST(ExpiringUnorderedSet, TestLifeTime)
{
    ExpiringUnorderedSet<std::string> s(2);
    const auto key = "key";
    ASSERT_TRUE(s.insert(key));
    ASSERT_TRUE(s.contains(key));

    sleep(3);

    ASSERT_FALSE(s.contains(key));
}

TEST(ExpiringUnorderedSet, TestManualCleanup)
{
    ExpiringUnorderedSet<std::string> s(1);
    ASSERT_TRUE(s.insert("alpha"));
    ASSERT_TRUE(s.insert("bravo"));
    ASSERT_TRUE(s.insert("charlie"));
    ASSERT_EQ(s.capacity(), 3);

    sleep(2);

    s.resize();
    ASSERT_EQ(s.capacity(), 0);
}

TEST(SelfCleaningExpiringUnorderedSet, TestAutomaticCleanup)
{
    SelfCleaningExpiringUnorderedSet<std::string> s(1, 2);
    ASSERT_TRUE(s.insert("alpha"));
    ASSERT_TRUE(s.insert("bravo"));
    ASSERT_TRUE(s.insert("charlie"));
    ASSERT_EQ(s.capacity(), 3);

    sleep(4);

    ASSERT_EQ(s.capacity(), 0);
}
