/*
Copyright (c) 2010 by Drake Justice <djustice.kde@gmail.com>

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 2 of the License, or
(at your option) any later version.

*/

#include <QFileInfo>
#include <QTimer>

#include "encoderthread.h"
#include <settings.h>
#include "videofile.h"

QTimer m_timer;

EncoderThread::EncoderThread(const QStringList& fileList, const QString& tmpDir, const QString& vidMode, const QString& aspectRatio)
{
    m_fileList = fileList;
    m_tmpDir = tmpDir;
    m_vidMode = vidMode;
    m_aspectRatio = aspectRatio;
    m_currentFile = 0;
}

EncoderThread::~EncoderThread()
{ }

void EncoderThread::run()
{
    m_ffmpegProcess.setProcessChannelMode(QProcess::MergedChannels);
    m_ffmpegProcess.start("ffmpeg -i \"" + m_fileList.at(m_currentFile) + "\" -y -target " + m_vidMode + "-dvd -sameq -aspect " + m_aspectRatio + " \"" + m_tmpDir + "/" + QFileInfo(m_fileList.at(m_currentFile)).baseName() + ".mpg" + "\"");

    emit progressFile(0);
    qDebug() << "EncoderThread's currentFileOutput: " + m_tmpDir + "/" + QFileInfo(m_fileList.at(m_currentFile)).baseName() + ".mpg";

    connect(&m_ffmpegProcess, SIGNAL(finished(int)), this, SLOT(ffmpegFinished(int)));
    connect(&m_timer, SIGNAL(timeout()), this, SLOT(updateProgress()));
    m_timer.start(800);

    exec();
}

void EncoderThread::ffmpegFinished(int i)
{
    qDebug() << "========== ffmpegFinished: " << i << "==============";
    m_currentFile++;

    if (i != 0) { return; }

    if (m_currentFile >= m_fileList.count()) {
      m_timer.stop();
      m_currentFile = 0;
      emit(finished());
      return;
    }

    emit progressFile(m_currentFile);

    m_ffmpegProcess.start("ffmpeg -i \"" + m_fileList.at(m_currentFile) + "\" -y -target " + m_vidMode + "-dvd -sameq -aspect " + m_aspectRatio + " \"" + m_tmpDir + "/" + QFileInfo(m_fileList.at(m_currentFile)).baseName() + ".mpg" + "\"");

    qDebug() << "EncoderThread's currentFileOutput: " + m_tmpDir + "/" + QFileInfo(m_fileList.at(m_currentFile)).baseName() + ".mpg";
}

void EncoderThread::mencoderFinished()
{
  
}

void EncoderThread::updateProgress()
{
    QString out = m_ffmpegProcess.readAll();
    qDebug() << out;
    VideoFile f(m_fileList.at(m_currentFile));
    emit progressMax(f.duration);
    foreach (QString line, out.split("\n")) {
        if (line.contains("time=")) {
            emit progress(line.split(".").at(1).right(5).split("=").at(1).toInt());
        }
    }
}
