#include "tools.h"
#include "cfg.h"
#include "globaldefine.h"
#include "program/pagelistitem.h"
#include "base/x_uimsgboxok.h"
#include <QBuffer>
#include <QJsonArray>

void Tools::timerEvent(QTimerEvent *event) {
    if(timer_id==event->timerId()) emit sTick();
}

Tools* Tools::getInstance() {
    static const auto ins = new Tools(qApp);
    return ins;
}

QRectF Tools::centerRect(qreal width, qreal height, int maxW, int maxH) {
    if(maxW < width || maxH < height) {
        auto rate = qMin(maxW / width, maxH / height);
        width *= rate;
        height *= rate;
    }
    return QRectF((maxW - width) / 2, (maxH - height) / 2, width, height);
}

QString Tools::addSufix(QString path) {
    int i = path.lastIndexOf('.');
    QString prefix = path, sufix;
    if(i > 0 && i > path.lastIndexOf('/')+1 && i >= path.length()-9) {
        prefix = path.left(i);
        sufix = path.mid(i);
    }
    i = 1;
    while(QFileInfo::exists(path = prefix+QString::number(i)+sufix)) i++;
    return path;
}

QString Tools::readErrStr(QImageReader::ImageReaderError err) {
    if(err==QImageReader::UnknownError) return "UnknownError";
    if(err==QImageReader::FileNotFoundError) return "FileNotFoundError";
    if(err==QImageReader::DeviceError) return "DeviceError";
    if(err==QImageReader::UnsupportedFormatError) return "UnsupportedFormatError";
    if(err==QImageReader::InvalidDataError) return "InvalidDataError";
    return QString::number(err);
}

QString Tools::fileMd5(QString filePath) {
    QFile file(filePath);
    if(! file.open(QFile::ReadOnly)) return QString();
    QCryptographicHash cryptoHash(QCryptographicHash::Md5);
    if(! cryptoHash.addData(&file)) {
        file.close();
        return QString();
    }
    file.close();
    return QString::fromLatin1(cryptoHash.result().toHex());
}
void Tools::mergeFormat(QTextEdit *textEdit, const QTextCharFormat &fmt) {
    QTextCursor cursor = textEdit->textCursor();
    if(! cursor.hasSelection()) cursor.select(QTextCursor::WordUnderCursor);
    cursor.mergeCharFormat(fmt);
}
void Tools::saveImg(const QString& dir, const QFontMetrics& metric, const QFont& font, const QColor& color, QJsonObject& imgs, const QString& str, const QString& name) {
    if(str.isEmpty()) return;
    QImage img(metric.horizontalAdvance(str), metric.lineSpacing(), QImage::Format_ARGB32);
    img.fill(Qt::transparent);
    {
        QPainter painter(&img);
        painter.setFont(font);
        painter.setPen(color);
        QTextOption opt(Qt::AlignCenter);
        opt.setWrapMode(QTextOption::NoWrap);
        painter.drawText(QRectF(0, 0, img.width(), img.height()), str, opt);
    }
    QByteArray data;
    QBuffer buffer(&data);
    buffer.open(QIODevice::WriteOnly);
    if(! img.save(&buffer, "PNG")) return;
    QCryptographicHash cryptoHash(QCryptographicHash::Md5);
    cryptoHash.addData(data);
    auto md5 = QString::fromLatin1(cryptoHash.result().toHex());
    QFile file(dir+"/"+md5);
    if(! file.open(QFile::WriteOnly)) return;
    file.write(data);
    file.close();
    imgs.insert(name, md5);
}
void Tools::saveImg2(const QString& dir, const QFontMetrics& metric, const QFont& font, const QColor& color, QJsonArray& imgs, const QString& str, const QString& name) {
    QJsonObject obj{
        {"name", name},
        {"mime", "image/png"}
    };
    if(! str.isEmpty()) {
        QImage img(metric.horizontalAdvance(str), metric.lineSpacing(), QImage::Format_ARGB32);
        img.fill(Qt::transparent);
        {
            QPainter painter(&img);
            painter.setFont(font);
            painter.setPen(color);
            QTextOption opt(Qt::AlignCenter);
            opt.setWrapMode(QTextOption::NoWrap);
            painter.drawText(QRectF(0, 0, img.width(), img.height()), str, opt);
        }
        QByteArray data;
        QBuffer buffer(&data);
        buffer.open(QIODevice::WriteOnly);
        if(img.save(&buffer, "PNG")) {
            obj.insert("picWidth", img.width());
            obj.insert("picHeight", img.height());
            QCryptographicHash cryptoHash(QCryptographicHash::Md5);
            cryptoHash.addData(data);
            auto md5 = QString::fromLatin1(cryptoHash.result().toHex());
            QFile file(dir+"/"+md5);
            if(file.open(QFile::WriteOnly)) {
                file.write(data);
                file.close();
                obj.insert("id", md5);
            }
        }
    }
    imgs.append(obj);
}

QBrush Tools::getBrush(const QColor& color) {
    return color.alpha()==0 ? Qt::NoBrush : QBrush(color);
}

int Tools::color2Int(const QColor& color) {
    int res = 0;
    res |= (color.red()   & 0xFF) << 24;
    res |= (color.green() & 0xFF) << 16;
    res |= (color.blue()  & 0xFF) <<  8;
    res |= (color.alpha() & 0xFF);
    return res;
}

QColor Tools::int2Color(int value) {
    QColor res;
    res.setRed  ((value >> 24) & 0xFF);
    res.setGreen((value >> 16) & 0xFF);
    res.setBlue ((value >>  8) & 0xFF);
    res.setAlpha((value      ) & 0xFF);
    return res;
}

QString Tools::selectStr(bool f, const QString &s0, const QString &s1) {
    return f ? s0 : s1;
}
