#include "DfuDeviceErrors.h"
#include <QString>
#include <QStringBuilder>
#include "LQError.h"
#include "libusb-1.0/libusb.h"


LQError DfuDeviceErrors::error(int code, const QString &msg) {
    static const QString err_type {QStringLiteral("dfudev")};
    return LQError{code, msg, err_type};
}

LQError DfuDeviceErrors::devNotDetected() {
    return error(-1, tr("device was not detected"));
}

LQError DfuDeviceErrors::devNotOpened() {
    return error(-2, tr("device is not opened"));
}

LQError DfuDeviceErrors::devOpen(int err_code) {
    return libUsbError(-3, tr("device open error"), err_code);
}

LQError DfuDeviceErrors::devIfaceClaim(int err_code) {
    return libUsbError(-4, tr("device interface claim error"), err_code);
}

LQError DfuDeviceErrors::devCtlReqFailed(int req_code, int err_code) {
    return libUsbError(-5, tr("device control request %1 failed").arg(req_code), err_code);
}

LQError DfuDeviceErrors::devCtlReqInsufSize(int req_code, int req_size, int done_size) {
        return error(-6, tr("device control request %1 was finished with insuffition data size (requested %2, done %3)")
                     .arg(req_code).arg(req_size).arg(done_size));
}

LQError DfuDeviceErrors::devStatusError(DfuDevice::Status status) {
    return error(-7, tr("device error status: %1").arg(static_cast<int>(status)));
}

LQError DfuDeviceErrors::libUsbError(int base_err, const QString &text, int err_code) {
    return error(base_err, text % QLatin1String(": ") %
                 tr("libusb error %1 - %2").arg(err_code).arg(QString::fromLatin1(libusb_error_name(err_code))));
}
