.. _ex-loginlogout:

Logging in/out
==============

The goal of this example is to create a C++ console application which logs in to a profile if the turret is logged out or is in Recieve Calls Only or log out if it is logged in.

For this we can start from the ``connect`` example found in :ref:`TurretApiSDK <turretapisdkcpp>`.

.. _ex-llnewproject:

Creating a new project
----------------------

We can copy the ``examples/connect`` folder and make some changes to create a new project.

#. Rename the folder to something different, eg. ``loginlogout``
#. Adding the new directory to the ``examples/CMakeLists.txt`` file

    .. code-block:: cmake

        add_subdirectory(loginlogout)

#. Renaming the C++ source file to ``loginlogout.cpp``
#. Modifying the ``examples/loginlogout/CMakeLists.txt`` file to incorporate our changes

    .. code-block:: cmake
       :linenos:
       :emphasize-lines: 3,4

        cmake_minimum_required(VERSION 3.13 FATAL_ERROR)

        add_executable(loginlogout loginlogout.cpp)
        target_link_libraries(loginlogout
          PRIVATE TurretApi
        )

    .. .. literalinclude:: /resources/loginlogout/CMakeLists.txt
    ..    :diff: /resources/connect/CMakeLists.txt
    ..    :linenos:
    ..    :lineno-match:

Adding the logic
----------------

For our application to work we need to first query the login state of the connected turret. Thankfully after inspecting the API we can see that there is a function on the interface just for this purpose, namely :thrift:service_method:`TurretApi.TurretRequestService.getLoginState`

Using that we can get the login state of the turret after the connection was made

.. code-block:: cpp
    :emphasize-lines: 2

        auto connection = osxpert::thrift::connect(client);
        osxpert::turret::api::TurretState loginState = connection->getLoginState();

The ``getLoginState`` function returns a :thrift:enum:`TurretApi.TurretState` so using the values generated into ``osxpert::turret::api::TurretState`` found in the ``TurretApi_types.h`` file we can check if the turret is logged in and act on it with the help of :thrift:service_method:`TurretApi.TurretRequestService.login` and :thrift:service_method:`TurretApi.TurretRequestService.logout`

.. code-block:: cpp

        if (loginState == osxpert::turret::api::TurretState::Login)
        {
          connection->logout();
        }
        else
        {
          connection->login("<profile name>", "<profile password>");
        }

And with that it should be complete.

.. note::

    This example can be found in :ref:`ThriftApiSDK <turretapisdkcpp>`. It uses the profile name "API Profile" and no password, but it also accepts command line arguments to change that eg. ``loginlogout.exe "Your Profile" "password"``