#include "file.h"

QProcess *File::m_process = nullptr;

MatAndFileinfo File::loadImage(QString path, ImreadModes modes)
{
    MatAndFileinfo maf = KylinImageCodec::loadThumbnailToMat(path, modes);
    //判断图像是否有效，无效设置为默认失败图片提示
    if (!maf.openSuccess) {
        //打开失败，将图片路径存起来，便于切换主题时，更改相册对应的图片icon
        if (!Variable::g_damagedImage.contains(path)) {
            Variable::g_damagedImage.append(path);
        }
        if (THEMEDARK == Variable::g_themeStyle || THEMEBLACK == Variable::g_themeStyle) {
            path = Variable::DAMAGED_IMAGE_BLACK;
        } else {
            path = Variable::DAMAGED_IMAGE_WHITE;
        }
        QImage img(path, "apng");
        maf.mat = Mat(img.height(), img.width(), CV_8UC4, const_cast<uchar *>(img.bits()),
                      static_cast<size_t>(img.bytesPerLine()))
                      .clone();
    }
    return maf;
}

bool File::saveImage(const Mat &mat, const QString &savepath, bool replace)
{
    return KylinImageCodec::saveImage(mat, savepath, replace);
}

bool File::saveImage(QList<Mat> *list, const int &fps, const QString &savepath, bool replace)
{
    return KylinImageCodec::saveImage(list, fps, savepath, replace);
}


void File::deleteImage(const QString &savepath)
{
    if (!QFile::exists(savepath)) {
        return;
    }
    processStart("gio", QStringList() << "trash" << savepath);
}

bool File::isSaving(const QString &path)
{
    return KylinImageCodec::isSaving(path);
}

bool File::allSaveFinish()
{
    return KylinImageCodec::allSaveFinish();
}

bool File::canDel(QString path)
{
    // gio获取fileinfo -- char
    //对于含有特殊字符的路径，url特殊字符需转义：%#等。g_file_new_for_uri是never fail，所以不用判空
    GFile *file = g_file_new_for_uri(QUrl::fromLocalFile(path).toString().toUtf8().constData());
    //参数：1.--file；2.--文件属性 ""代表获取所有属性，access::* --
    //代表可获得的所有boolean属性；3.先设置默认属性；4.和5.nullptr即可
    GFileInfo *fileInfo =
        g_file_query_info(file, "access::*," G_FILE_ATTRIBUTE_ID_FILE, G_FILE_QUERY_INFO_NONE, nullptr, nullptr);
    //判空-返回false
    if (!fileInfo) {
        return false;
    }
    bool canwrite = g_file_info_get_attribute_boolean(fileInfo, G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE);
    bool candel = g_file_info_get_attribute_boolean(fileInfo, G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH);

    if (canwrite && candel) {
        return true;
    } else {
        return false;
    }
}

QString File::savePath()
{
    return KylinImageCodec::savePath();
}

void File::processStart(const QString &cmd, QStringList arguments)
{
    if (m_process == nullptr) {
        // File构造函数是在主线程调用的，m_process如果在构造函数中实例化，会报错
        m_process = new QProcess; //操作文件
        connect(m_process, &QProcess::readyReadStandardError, [=] {
            qDebug() << "*******process error*******\n"
                     << QString::fromLocal8Bit(m_process->readAllStandardError()) << "\n*******process error*******";
        });
    }

    m_process->start(cmd, arguments);
    m_process->waitForStarted();
    m_process->waitForFinished();
}
