/*
 * (c) 2015 Mechatronik Karl Zeilhofer
 * karl@zeilhofer.co.at
 *
 * If you want to use or modify the sourcecode, please contact me.
 */

#include "restorer.h"
#include <QDir>
#include <QFileInfoList>
#include <QFileInfo>
#include <QDebug>


Restorer::Restorer(QObject *parent) : QObject(parent)
{

}

void Restorer::process(QString rootDirPath)
{
    static int level = 0;

    level ++;
    //qDebug() << "called process() with QString = " << rootDirPath;
    QDir rootDir(rootDirPath);
    //qDebug() << "QDir rootDir.absolutePath() = " << rootDir.absolutePath();
    qDebug() << "processing " << rootDir.absolutePath() << "...";
    QFileInfoList dirList = rootDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);

    foreach (QFileInfo dirInfo, dirList) {
        QDir dir(dirInfo.absoluteFilePath());
        //qDebug() << "go into:" << dir.absolutePath();
        process(dir.absolutePath());
    }

    QFileInfoList fileList = rootDir.entryInfoList(QDir::Files|QDir::Hidden);
    foreach (QFileInfo fileInfo, fileList) {
        //QDir dir(dirInfo.absoluteFilePath());
        //qDebug() << "go into:" << dir.absolutePath();
        restore(fileInfo.absoluteFilePath());
    }
    level--;

    if(level == 0)
    {
        emit finished();
    }
}

void Restorer::restore(QString absoluteFilePath)
{
    qDebug() << "  restoring" << absoluteFilePath;

    int i1 = absoluteFilePath.lastIndexOf("(");
    if(i1 != -1)
        i1--; // include space before date-time-string
    int i2 = absoluteFilePath.lastIndexOf(")");

    if(i2 <= i1 || !absoluteFilePath.mid(i1, i2-i1+1).contains("UTC"))
    {
        qDebug() << "ERROR: no date extension found in" << absoluteFilePath;
        emit currentFileNameChanged(QString("skipping ").append(absoluteFilePath));
        return;
    }

    QString newFileName = absoluteFilePath.left(i1);
    newFileName = newFileName.append(absoluteFilePath.right(absoluteFilePath.length()-i2-1));

    emit currentFileNameChanged(newFileName);
    //ui->label_currentFile->setText(newFileName);

    QFileInfo newFile(newFileName);
    if(newFile.exists())
    {
        bool ret = QFile::remove(newFileName);

        // delete old restoration:
//        QProcess p;
//        QStringList args;
//        args.append(QString("\"").append(newFileName).append("\""));
//        p.setArguments(args);
//        p.start("del");
//        p.waitForFinished(5000);
//        int ret = p.exitCode();

        if(ret == false)
        {
            qDebug() << "ERROR on deleting file " << newFileName;
        }else
        {
            qDebug() << "    , but beofre we removed existing file";
        }
    }
    QFile::rename(absoluteFilePath, newFileName);
    QFile f(newFileName);
    f.setPermissions(QFile::WriteOther);
}
