#include "DownloadFileUtil.h"

DownloadFileUtil::DownloadFileUtil()
{

}

bool DownloadFileUtil::downloadFileLocal(QString sourcePath, QString destPathName, int& errCode)
{
    errCode = 0;
    destPathName.replace("\\", "/");
    if (sourcePath == destPathName) {
        return true;
    }
    if (!QFile::exists(sourcePath)){
        errCode = 101; // 源文件不存在
        return false;
    }
    QDir * createfile = new QDir;
    bool exist = createfile->exists(destPathName);
    if (exist) {
        createfile->remove(destPathName);
    } // end if

    if(!QFile::copy(sourcePath, destPathName))
    {
        // 复制文件失败
        errCode = 102;
        return false;
    }
    return true;
}

bool DownloadFileUtil::uploadFileLocal(QString localFile, QString remoteFileUrl, int &errCode)
{
    errCode = 0;

    remoteFileUrl.replace("\\", "/");
    localFile.replace("\\", "/");
    if (remoteFileUrl == localFile) {
        return true;
    }
    if (!QFile::exists(localFile)){
        errCode = 101; // 源文件不存在
        return false;
    }

    QDir destDir(SettingConfig::getInstance().BASE_RES_FILE_PATH);
    if (!destDir.exists()) {
        bool createDir = destDir.mkpath("."); // 递归创建目录
        if (createDir == false) {
            // 目标文件夹创建失败
            errCode = 103;
            return false;
        }
    }

    if(!QFile::copy(localFile, remoteFileUrl))
    {
        // 复制文件失败
        errCode = 102;
        return false;
    }

    return true;
}
