/*
 * Copyright (C) 2020 Uniontech Technology Co., Ltd.
 *
 * Author:     xinbo wang <wangxinbo@uniontech.com>
 *
 * Maintainer: xinbo wang <wangxinbo@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 "SecurityTool.h"

#include "dnd_security.h"

#include <QDebug>

int SecurityTool::handleSecurityVerify(void *data, int types, int client, int target)
{
    qWarning() << __func__ << __LINE__ << " handle copy verify types " << types << " from client " << client << " to " << target;
    SecurityTool *tool = reinterpret_cast<SecurityTool *>(data);
    return tool->doSecurityVerify(types, client, target);
}

int SecurityTool::doSecurityVerify(int types, int client, int target)
{
    if (m_verifiyLog.size() > 100) {
        m_verifiyLog.remove(1, 10);
    }
    m_verifiyLog.append(QString("type:%1 from:%2 to:%3 permission:%4").arg(types).arg(client).arg(target).arg(m_permission));
    return m_permission;
}

SecurityTool::SecurityTool(QObject *parent)
    : QObject(parent)
    , m_permission(PermissionDeny)
{
    InitDtkDisplay();
    DoSecurityVerifyCallback(this, handleSecurityVerify);
    m_sessionId = GetSecuritySession(SecClipboardCopy);
    qWarning() << __func__ << __LINE__ << " new SecuritySession " << m_sessionId;
}

SecurityTool::~SecurityTool()
{
    qWarning() << __func__ << __LINE__ << " new SecuritySession " << m_sessionId;
    DestroySecuritySession(m_sessionId);
    DestoryDtkDisplay();
}

int SecurityTool::setPermission(int permission)
{
    if (permission != PermissionDeny && permission != PermissionAllow && permission != PermissionDelay) {
        return -1;
    }
    m_permission = permission;
    return permission;
}

QString SecurityTool::dump()
{
    QString info = "session id:";
    info.append(QString("%1").arg(m_sessionId));
    info.append("\n");

    info.append("permission:");
    info.append(QString("%1").arg(m_permission));
    info.append("\n");

    QVector<QString>::iterator iter;
    for (iter = m_verifiyLog.begin(); iter != m_verifiyLog.end(); iter++) {
        info.append(*iter);
        info.append("\n");
    }

    return info;
}