Application::Application(QWidget *parent) :
    QObject(parent)
{
    createWidgets();
}

void Application::createWidgets() {
    trackingActiveIcon = new QIcon(":tray/tracking-active");
    trackingStoppedIcon = new QIcon(":tray/tracking-stopped");

    contextMenu = new QMenu();
    buildMenu(*contextMenu);

    trayIcon = new QSystemTrayIcon(*trackingStoppedIcon);
    trayIcon->setContextMenu(contextMenu);
    trayIcon->show();
}

Application::~Application() {
}

void Application::quit() {
    stopTracking();
    exit(0);
}

void Application::stopTracking() {
    activityTracker.stopTracking();
    trayIcon->setIcon(*trackingStoppedIcon);
}

void Application::startTracking(QAction *qAction) {
    const Task* task = (const Task*)qAction->data().value<void*>();
    startTracking(*task);
}

void Application::startTracking(const Task& task) {
    activityTracker.startTracking(task);
    trayIcon->setIcon(*trackingActiveIcon);
}

void Application::createTask() {
    TaskSelectDialog* taskSelectDialog = new TaskSelectDialog(taskProvider);
    taskSelectDialog->show();
}

void Application::buildMenu(QMenu& menu) {

    buildTaskMenuActions(menu);

    menu.addSeparator();

    QAction* createTaskAction = new QAction(tr("New task..."), this);
    connect(createTaskAction, SIGNAL(triggered()), this, SLOT(createTask()));
    menu.addAction(createTaskAction);

    menu.addSeparator();

    stopAction = new QAction(tr("&Stop tracking"), this);
    connect(stopAction, SIGNAL(triggered()), this, SLOT(stopTracking()));
    menu.addAction(stopAction);

    QAction *quitAction = new QAction(tr("&Quit"), this);
    connect(quitAction, SIGNAL(triggered()), this, SLOT(quit()));
    menu.addAction(quitAction);
}

void Application::buildTaskMenuActions(QMenu& menu) {
    for (auto task : taskProvider.getRecentTasks()) {
        QAction *taskAction = new QAction(task->getName().c_str(), this);
        taskAction->setData(QVariant::fromValue((void*)task));
        connect(taskAction, &QAction::triggered, [=](){ startTracking(taskAction); });
        menu.addAction(taskAction);
    }
}
