/*
 * Copyright: 2015 Canonical Ltd.
 *
 * This file is part of lomiri-terminal-app
 *
 * lomiri-terminal-app 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.
 *
 * lomiri-terminal-app 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/>.
 *
 * Author: Filippo Scognamiglio <flscogna@gmail.com>
 */

#include "fileio.h"

#include <QRandomGenerator>

FileIO::FileIO()
{
}

bool FileIO::write(const QString& sourceUrl, const QString& data) {
    if (sourceUrl.isEmpty())
        return false;

    QFile file(sourceUrl);
    if (!file.open(QFile::WriteOnly | QFile::Truncate))
        return false;

    QTextStream out(&file);
    out << data;
    file.close();
    return true;
}

QString FileIO::read(const QString& sourceUrl) {
    if (sourceUrl.isEmpty())
        return "";

    QFile file(sourceUrl);
    if (!file.open(QFile::ReadOnly))
        return "";

    QTextStream in(&file);
    QString result = in.readAll();

    file.close();

    return result;
}

QString FileIO::mktemp(const QString& tmpl) {
    const QString chars("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
    QString tmpnam = QString(tmpl);
    for (auto i = 0; i < 16; i++) {
        auto x = QRandomGenerator::global()->bounded(0, chars.length() - 1);
        tmpnam.append(chars.at(x));
    }
    return tmpnam;
}

bool FileIO::remove(const QString& fileName) {
    return QFile::remove(fileName);
}

QString FileIO::symLinkTarget(const QString& fileName) {
    return QFile::symLinkTarget(fileName);
}

bool FileIO::exists(const QString & fileName) {
    return QFile::exists(fileName);
}
