/***************************** LICENSE START ***********************************

 Copyright 2016 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "MvQFileInfo.h"

#include <QDateTime>

QString MvQFileInfo::formatSize() const
{
    return formatSize(size());
}

QString MvQFileInfo::formatModDate() const
{
    QDateTime dt = lastModified();
    return dt.toString("yyyy-MM-dd hh:mm:ss");
}

QString MvQFileInfo::formatPermissions() const
{
    QString str(permission(QFile::ReadOwner) ? "r" : "-");
    str += (permission(QFile::WriteOwner) ? "w" : "-");
    str += (permission(QFile::ExeOwner) ? "x" : "-");
    str += (permission(QFile::ReadGroup) ? "r" : "-");
    str += (permission(QFile::WriteGroup) ? "w" : "-");
    str += (permission(QFile::ExeGroup) ? "x" : "-");
    str += (permission(QFile::ReadOther) ? "r" : "-");
    str += (permission(QFile::WriteOther) ? "w" : "-");
    str += (permission(QFile::ExeOther) ? "x" : "-");

    return str;
}

QString MvQFileInfo::formatSize(qint64 size)
{
    if (size < 1024)
        return QString::number(size) + " B";
    else if (size < 1024 * 1024)
        return handleSizePrecision(((double)size) / 1024, "KB");
    else if (size < 1024 * 1024 * 1024)
        return handleSizePrecision(((double)size) / (1024 * 1024), "MB");
    else
        return handleSizePrecision(((double)size) / (1024 * 1024 * 1024), "GB");

    return {};
}

QString MvQFileInfo::handleSizePrecision(double sizeInUnits, QString unitsString)
{
    // if less than 10, use one decimal place, otherwise round to the nearest int
    if (sizeInUnits < 10)
        return QString::number(sizeInUnits, 'f', 1) + " " + unitsString;
    else
        return QString::number((unsigned int)(sizeInUnits + 0.5)) + " " + unitsString;
}
