/*
 * Squawk messenger.
 * Copyright (C) 2019  Yury Gubich <blue@macaw.me>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "pathcheck.h"

QRegularExpression squawk("^squawk:\\/\\/");
QString Shared::downloadsPathCheck()
{
    QSettings settings;
    QVariant dpv = settings.value("downloadsPath");
    QString path;
    if (!dpv.isValid()) {
        path = defaultDownloadsPath();
        qDebug() << "no downloadsPath variable in config, using default" << path;
        path = getAbsoluteWritablePath(path);
        return path;
    } else {
        path = dpv.toString();
        path = getAbsoluteWritablePath(path);
        if (path.size() == 0) {
            path = defaultDownloadsPath();
            qDebug() << "falling back to the default downloads path" << path;
            path = getAbsoluteWritablePath(path);
        }
        return path;
    }
}

QString Shared::defaultDownloadsPath()
{
    return QStandardPaths::writableLocation(QStandardPaths::DownloadLocation) + "/" + QApplication::applicationName();
}

QString Shared::getAbsoluteWritablePath(const QString& path)
{
    QDir location(path);
    if (!location.exists()) {
        bool res = location.mkpath(location.absolutePath());
        if (!res) {
            qDebug() << "couldn't create directory" << path;
            return "";
        }
    }
    QFileInfo info(location.absolutePath());
    if (info.isWritable()) {
        return location.absolutePath();
    } else {
        qDebug() << "directory" << path << "is not writable";
        return "";
    }
}

QString Shared::resolvePath(QString path)
{
    QSettings settings;
    QVariant dpv = settings.value("downloadsPath");
    return path.replace(squawk, dpv.toString() + "/");
}

QString Shared::squawkifyPath(QString path)
{
    QSettings settings;
    QString current = settings.value("downloadsPath").toString();

    if (path.startsWith(current)) {
        path.replace(0, current.size() + 1, "squawk://");
    }

    return path;
}

bool Shared::isSubdirectoryOfSettings(const QString& path)
{

    QSettings settings;
    QDir oldPath(settings.value("downloadsPath").toString());
    QDir newPath(path);

    return newPath.canonicalPath().startsWith(oldPath.canonicalPath());
}