#include "clientthread.h"

clientThread::clientThread(QTcpSocket &Tsocket, QString TpeerIP, QStringList &list)
{
    peerIP = TpeerIP;
    socket = &Tsocket;
    QStringList list2;

    connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
    connect(this, SIGNAL(forceReadyRead()), this, SLOT(readyRead()));
    list2 = parseList(list);

    for (int i = 0; i < list.count(); i++)
    {
        socket->write("f " + list2.at(i).toLocal8Bit() + "\n");
        socket->flush();
        qDebug() << list2.at(i);
    }
}

clientThread::~clientThread()
{
    qDebug() << "Ending thread";
}

void clientThread::updateFileList(QStringList list)
{
    //QStringList list2 = parseList(list);

    for (int i = 0; i < list.count(); i++)
    {
        socket->write("f " + list.at(i).toLocal8Bit() + "\n");
        socket->flush();
        qDebug() << list.at(i);
    }
}

QStringList clientThread::parseList(QStringList list)
{
    QStringList temp;
    QString tempStr;

    for (int i = 0; i < list.count(); i++)
    {
        tempStr = list.at(i);
        tempStr = tempStr.mid(tempStr.lastIndexOf("/") + 1, (tempStr.count() - tempStr.lastIndexOf("/") - 5));
        temp.append(tempStr);
    }

    return temp;
}

void clientThread::run()
{
    finish = false;
    emit this->forceReadyRead();
    // Do nothing but wait
    while (finish == false);
    return;
}

void clientThread::sendStatus(QString stat)
{
    //socket->write(stat.toLocal8Bit() + "\n");
    //socket->flush();
    //socket->waitForBytesWritten(3000);
}

void clientThread::sendTime(double pos, double total)
{
    socket->write((QString("Time elapsed: ") + QString::number((int) pos) + QString(" / ") + QString::number((int) total)).toLocal8Bit() + '\n');
    socket->flush();
    //socket->waitForBytesWritten(500);
}

void clientThread::readyRead()
{
    QString read;

    qDebug() << "Reading..." << socket->bytesAvailable();
    read = socket->readAll();
    qDebug() << read << endl;

    if (read.contains("QUIT ###"))
    {
        socket->close();
        qDebug() << "Terminating connection.\n";
        emit askForClose(peerIP);
        finish = true;
        return;
    }
    else
    {
        emit recvCommand(read);
    }
}
