/**
 * \file    Mimic_Command.cpp
 * \author  Silvan Murer
 * \date    13 October 2022
 *
 * \brief   Command class of genSDK GF implementation, based on Mimic_Node
 */

#include "features/Mimic_Command.hpp"
#include "Mimic_Exception.hpp"

#define GENICAM_NO_AUTO_IMPLIB
#include "GenICam.h"

#include <memory>
#include <string>

using namespace GenApi;

namespace mimic {

    Mimic_Command::Mimic_Command() : Mimic_Node() { type = Type_e::COMMAND; };
    Mimic_Command::Mimic_Command(GenApi_3_4::INode* node) : Mimic_Node(node) { type = Type_e::COMMAND; };
    Mimic_Command::~Mimic_Command() { };

    std::variant<int64_t, double, bool, std::string> Mimic_Command::getVariant(std::string name)
    {
        return isDone();
    };
    void Mimic_Command::setVariant(std::string name, std::variant<int64_t, double, bool, std::string> value)
    {
        try {
            if (std::holds_alternative<bool>(value) && std::get<bool>(value)) {
                execute();
            }
            else if (std::holds_alternative<int64_t>(value) && std::get<int64_t>(value)) {
                execute();
            }
        }
        catch (std::bad_variant_access const& e) {
            throw Mimic_Access_Exception(std::string("Node ") + node->GetName().c_str() + " is of type Command! " + e.what(), -650);
        }
        catch (...) {
            throw Mimic_Access_Exception(std::string("Node ") + node->GetName().c_str() + " read failed!", -610);
        }

    }

    void Mimic_Command::execute()
    {
        if (!IsImplemented(node) || !IsAvailable(node) || !IsWritable(node)) {
            throw Mimic_Access_Exception(std::string("Node ") + node->GetName().c_str() + " is not writable!", -600);
        }
        try {
            dynamic_cast<ICommand*>(node)->Execute();
        }
        catch (...) {
            throw Mimic_Access_Exception(std::string("Node ") + node->GetName().c_str() + " write failed!", -610);
        }
    }
    bool Mimic_Command::isDone()
    {
        if (!IsImplemented(node) || !IsAvailable(node) || !IsReadable(node)) {
            throw Mimic_Access_Exception(std::string("Node ") + node->GetName().c_str() + " is not readable!", -600);
        }
        try {
            return dynamic_cast<ICommand*>(node)->IsDone();
        }
        catch (...) {
            throw Mimic_Access_Exception(std::string("Node ") + node->GetName().c_str() + " read failed!", -610);
        }
    }
    

} /* namespace genSDK */
