#include <xavia/error.h>
#include <xavia/iSensor.h>
#include <xavia/logs.h>
#include <xavia/sensorFactory.h>

#include <chrono>
#include <cstdlib>
#include <iostream>
#include <thread>

namespace xsdk = xavia::sdk;

/*  EXAMPLE: POWER OFF/REBOOT
 *
 * This example shows how to power off and reboot a sensor.
 * First, a connection with the sensor needs to be established.
 * Then either Reboot() or Poweroff() can be called on the sensor object.
 *
 * If the command cannot be transmitted, an exception is thrown.
 * In all other cases, the command is processed by the sensor and will be
 * executed after some time.
 *
 * In both scenarios, the sensor object is no longer valid and should be disposed.
 * Use the factory to create a new sensor object.
 *
 * The example demonstrates:
 * 1. Connecting to a sensor using the SensorFactory
 * 2. Rebooting the sensor
 * 3. Waiting for the sensor to come back online
 * 4. Powering off the sensor
 *
 * Note: After rebooting, the sensor connection is lost and a new connection must
 * be established to continue operations.
 */

int main()
{
    std::cout << "=== Starting Poweroff Example ===" << std::endl;

    xsdk::SensorFactory factory;

    try
    {
        auto sensor = factory.Build();

        // Reboot the device
        std::cout << "Rebooting sensor..." << std::endl;
        sensor->Reboot();

        // Clean up the sensor object. The current connection has been severed.
        sensor.reset();

        std::cout << "Waiting 30 seconds..." << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(30));

        // Create a new sensor object via the Build function.
        // Calling build attempts to establish a new connection to the sensor.
        sensor = factory.Build();

        // Power off the device
        std::cout << "Powering off sensor..." << std::endl;
        sensor->Poweroff();
        std::cout << "Device powered off." << std::endl;
    }
    catch(const std::exception& e)
    {
        std::cerr << "Error received: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }

    std::cout << "=== Poweroff Example Completed ===" << std::endl;
    return EXIT_SUCCESS;
}
