/*
*  qm_task.cpp
*  QUIMUP thread worker class
*  © 2008-2024 Johan Spee
*  SPDX-License-Identifier: GPL-3.0-or-later
*/

#include "qm_task.h"
// for 'sleep_for':
#include <chrono>
#include <thread>


qm_workerTask::qm_workerTask()
{
    p_conn = nullptr;
    result = MPD_ERROR_CLOSED;
    b_success = false;
    b_abort = false;
    tries = 10;  // number of loops
    delay = 500; // msec delay in the loop
    server_name ="localhost";
    server_port = 6600;
    timeout = 5000; // msec
}


void qm_workerTask::abort_loop()
{
    b_abort = true;
}


void qm_workerTask::set_tries_delay (int num, int msec)
{
    tries = num;
    delay = msec;
}


void qm_workerTask::set_host_port_tmout(QString host, uint port, int timeout_ms )
{
    server_name = host;
    server_port = port;
    timeout = timeout_ms;
}


void qm_workerTask::do_work()
{
    int count = 1;
    do
    {
        printf("Connecting: try %i\n", count);
        b_success = false;
        count++;

        p_conn = mpd_connection_new( static_cast<const char*>(server_name.toUtf8()), static_cast<uint>(server_port), timeout);
        if (p_conn == nullptr)
        {
            result = MPD_ERROR_CLOSED;
        }
        else
        {
            result = mpd_connection_get_error(p_conn);
        }

        if (result == MPD_ERROR_SUCCESS)
        {
            b_success = true;
        }
        else
        {
            // printf("MPD not running?\n");
            std::this_thread::sleep_for(std::chrono::milliseconds(delay));
        }
        mpd_connection_clear_error(p_conn);
    }
    while (!b_abort && !b_success && count <= tries);

    // connected but aborted
    if (b_success && b_abort)
    {
        if (p_conn != nullptr)
            mpd_connection_free(p_conn);
        p_conn = nullptr;
        result = MPD_ERROR_CLOSED;
    }

    b_abort = false;

    emit work_done(result);
}

qm_workerTask::~qm_workerTask()
{

}
