/*
 * Copyright (c) 2025-2026 IB-Robot Group & openEuler Embedded SIG & openharmony-robot sig_RoboFrame.
 * 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.
 */

#pragma once

#include <concepts>
#include <functional>
#include <type_traits>

namespace ibmw::common::util {
// The following source code is from trpc-cpp.
// Copied and modified from
// https://github.com/trpc-group/trpc-cpp/blob/v1.2.0/trpc/util/deferred.h

class Deferred {
public:
    Deferred() = default;

    template <class F>
        requires(!std::same_as<std::decay_t<F>, Deferred>) // Avoid hide Deferred(Deferred&&)
    explicit Deferred(F&& f) : action_(std::forward<F>(f))
    {}

    Deferred(Deferred&&) noexcept = default;
    Deferred& operator=(Deferred&&) noexcept = default;

    ~Deferred()
    {
        if (action_) {
            action_();
        }
    }

    explicit operator bool() const noexcept { return !!action_; }

    void Dismiss() noexcept { action_ = nullptr; }

private:
    std::function<void()> action_;
};
// End of the source code from trpc-cpp.

} // namespace ibmw::common::util