/*
 * Copyright (C) 2023 Uniontech Technology Co., Ltd.
 *
 * Author:     zhijie geng <gengzhijie@uniontech.com>
 *
 * Maintainer: zhijie geng <gengzhiejie@uniontech.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * 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/>.
*/

#include "client.h"
#include "session.h"

#include <fstream>
#include <sys/prctl.h>
#include <unistd.h>
#include <pwd.h>

static char* readSessionManagerConnection()
{
    // TODO: read env from startdde
    // return std::getenv("SESSION_MAMAGER");
    char *connection = nullptr;
    data->entry = getpwuid(geteuid());
    std::ifstream file(std::string("/tmp/session_manager_") + data->entry->pw_name);
    std::string line;

    if (!file.is_open()) {
        return nullptr;
    }
    if (std::getline(file, line)) {
        line.erase(0, line.find_first_not_of(" "));
        line.erase(line.find_last_not_of(" ") + 1);
        connection = static_cast<char *>(malloc(line.length() + 1));
        strcpy(connection, line.c_str());
    }
    file.close();
    return connection;
}

USMClient::USMClient()
{
}

USMClient::USMClient(unsigned long long wid)
{
    char errorMsg[256] = { 0 };
    char *connection = readSessionManagerConnection();

    if (connection == nullptr) {
        return;
    }
    if (data->clientId != nullptr) {
        free(data->clientId);
        data->clientId = nullptr;
    }
    m_conn = SmcOpenConnection(connection,
                               nullptr,
                               1,
                               0,
                               SmcSaveYourselfProcMask |
                               SmcDieProcMask |
                               SmcSaveCompleteProcMask |
                               SmcShutdownCancelledProcMask,
                               &data->callbacks,
                               data->previousId,
                               &data->clientId,
                               255,
                               errorMsg);
    if (data->clientId == nullptr) {
        return;
    }

    // prctl(PR_GET_NAME, data->processName, 0, 0, 0);
    
    data->fullFilenames.emplace(wid, "session/" + QCoreApplication::applicationName().toStdString() +
                                     "_" + std::string(data->clientId) + "_" +
                                     std::to_string(data->tv.tv_sec) + "_" +
                                     std::to_string(data->tv.tv_usec));
    m_notifier = new QSocketNotifier(IceConnectionNumber(SmcGetIceConnection(m_conn)),
                                     QSocketNotifier::Read, this);
    connect(m_notifier, &QSocketNotifier::activated, this, &USMClient::processData);
    if (connection) {
        free(connection);
    }
    if (data->previousId != nullptr) {
        free(data->previousId);
        data->previousId = nullptr;
    }
}

void USMClient::processData() {
    if (m_conn != nullptr) {
        IceProcessMessages(SmcGetIceConnection(m_conn), nullptr, nullptr);
    }
}