/*
 * Copyright (C) 2014 Canonical Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program 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/>.
 *
 * Authored by Jussi Pakkanen <jussi.pakkanen@canonical.com>
 *
 */

#include "resultcollector.h"
#include <unity/scopes/SearchReply.h>

using namespace unity::scopes;

void ResultCollector::push(CategorisedResult result) {
    std::unique_lock<std::mutex> lock(mutex_);
    result_list_.emplace_back(std::move(result));
}

void ResultCollector::finished(ListenerBase::Reason /*reason*/, std::string const& /*error_message*/) {
    std::unique_lock<std::mutex> lock(mutex_);
    query_finished_ = true;
    condvar_.notify_one();
}

bool ResultCollector::wait_until_finished(int timeout_ms)
{
    std::unique_lock<std::mutex> lock(mutex_);
    if (timeout_ms >= 0)
    {
        return condvar_.wait_for(lock, std::chrono::milliseconds(timeout_ms),
                                 [this] { return this->query_finished_; });
    }
    else
    {
        condvar_.wait(lock, [this] { return query_finished_; });
        return true;
    }
}

std::list<unity::scopes::CategorisedResult> ResultCollector::take_results()
{
    std::list<unity::scopes::CategorisedResult> ret;
    std::unique_lock<std::mutex> lock(mutex_);
    result_list_.swap(ret);

    return ret;
}
