/*
 * This file is part of ArmarX.
 *
 * ArmarX is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * ArmarX is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    RobotAPI::ArmarXObjects::SkillObserver
 * @author     Raphael Grimm ( raphael dot grimm at kit dot edu )
 * @date       2020
 * @copyright  http://www.gnu.org/licenses/gpl-2.0.txt
 *             GNU General Public License
 */

#pragma once

#include <thread>
#include <string>
#include <vector>
#include <mutex>
#include <map>

#include <ArmarXCore/core/Component.h>

#include <ArmarXCore/libraries/ArmarXCoreComponentPlugins/DebugObserverComponentPlugin.h>

#include <RobotAPI/interface/skills/SkillObserverInterface.h>



namespace armarx::skills
{
    /**
     * @defgroup Component-SkillObserver SkillObserver
     * @ingroup RobotAPI-Components
     * A description of the component SkillObserver.
     *
     * @class SkillObserver
     * @ingroup Component-SkillObserver
     * @brief Brief description of class SkillObserver.
     *
     * Detailed description of class SkillObserver.
     */
    class SkillObserver :
        virtual public Component,
        virtual public SkillObserverInterface,
        virtual public DebugObserverComponentPluginUser
    {
    public:
        /// @see armarx::ManagedIceObject::getDefaultName()
        std::string getDefaultName() const override;
    protected:

        void onInitComponent()       override;
        void onConnectComponent()    override;
        void onDisconnectComponent() override;
        void onExitComponent()       override;

        armarx::PropertyDefinitionsPtr createPropertyDefinitions() override;

        ProviderSkillsSeq getSkills(const Ice::Current& = Ice::emptyCurrent) const override;
        void skillsProvided(const SkillProviderInterfacePrx& provider, const SkillDescriptionMap& skills, const Ice::Current& = Ice::emptyCurrent) override;
        void removeProvider(const SkillProviderInterfacePrx& provider, const Ice::Current& = Ice::emptyCurrent) override;
    private:
        void update_task();
        static long timestamp();

    private:
        using ProviderSkillsMap = std::map<SkillProviderInterfacePrx, ProviderSkills>;

        mutable std::mutex _skills_mutex;
        ProviderSkillsMap  _skills;

        std::atomic_bool   _stop_update_thread{false};
        std::atomic_bool   _scan_for_skills{true};
        std::thread        _update_thread;
        std::atomic_size_t _update_thread_period_ms{100};
    };
}