#include "filehandler.h"
#include <QFile>
#include <QIODevice>
#include <QTextStream>
#include <QDir>
#include <QDateTime>

#define SOURCES_FILE "/etc/apt/sources.list"
#define SOURCES_DIR "/etc/apt/sources.list.d"

FileHandler::FileHandler(QObject *parent) : QObject(parent)
{

}

void FileHandler::correctSources()
{
    QFile file(SOURCES_FILE);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        emit correctingSourcesFinishedWithError(file.errorString());
        return;
    }

    QDir dir(SOURCES_DIR);
    dir.setNameFilters(QStringList() << "*.*");
    dir.setFilter(QDir::Files);

    foreach(QString dirFile, dir.entryList())
    {
        if(!dir.remove(dirFile)) {
            emit correctingSourcesFinishedWithError("Could not delete " + dirFile);
            return;
        }
    }

    QDateTime time = QDateTime::currentDateTime();

    QTextStream out(&file);
    out << "### The Official Pardus Package Repositories ###" << "\n\n"
        << "deb http://depo.pardus.org.tr/pardus ondokuz main contrib non-free" << "\n"
        << "# deb-src http://depo.pardus.org.tr/pardus ondokuz main contrib non-free" << "\n\n"
        << "deb http://depo.pardus.org.tr/guvenlik ondokuz main contrib non-free" << "\n"
        << "# deb-src http://depo.pardus.org.tr/guvenlik ondokuz main contrib non-free" << "\n\n"
        << "### This section generated by Pardus Store at "
        << time.toString("hh:mm:ss - dd.MM.yyyy") << " ###\n";

    file.close();
    emit correctingSourcesFinished();
}
