#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    threadID = 0;
    musicThread = new channelthread(this);
    musicThread->start(QThread::HighestPriority);
    connect(this, SIGNAL(play(QString)), musicThread, SLOT(play(QString)));
    connect(this, SIGNAL(pause()), musicThread, SLOT(pause()));
    connect(this, SIGNAL(resume()), musicThread, SLOT(resume()));
    connect(this, SIGNAL(stop()), musicThread, SLOT(stop()));
    connect(this, SIGNAL(openPort(QString)), musicThread, SLOT(portOpen(QString)));
    connect(this, SIGNAL(closePort()), musicThread, SLOT(portClose()));
    connect(this, SIGNAL(next()), this, SLOT(nextSong()));
    connect(musicThread, SIGNAL(curPos(double, double)), this, SLOT(updatePos(double, double)));
    connect(musicThread, SIGNAL(endOfPlayback()), this, SLOT(nextSong()));
    connect(this, SIGNAL(changePos(int)), musicThread, SLOT(changePosition(int)));
    connect(this, SIGNAL(checkChange(bool)), musicThread, SLOT(checkBoxChange(bool)));
    currentFilepath = QString("");
    Bpause = false;
    Bsliderpressed = false;
}

MainWindow::~MainWindow()
{
    server->close();
    musicThread->exit(0);
    delete ui;
}

void MainWindow::updatePos(double position, double total)
{
    ui->label_4->setText(QString::number((int) position));
    if (ui->horizontalSlider->maximum() != total)
        ui->horizontalSlider->setMaximum(total);
    if (Bsliderpressed == false)
        ui->horizontalSlider->setSliderPosition(position);
}

void MainWindow::on_pushButton_clicked()
{
    server = new QTcpServer(this);

    connect(server,SIGNAL(newConnection()),this,SLOT(newConnection()));

    if(!server->listen(QHostAddress::Any, 2000))
        qDebug() << "Server could not start!";
    else
        qDebug() << "Server started";
}

void MainWindow::newConnection()
{
    socket = server->nextPendingConnection();
    ui->listWidget->addItem(socket->peerAddress().toString());
    threads[threadID] = new clientThread(*socket, socket->peerAddress().toString(), this->fileList);
    threads[threadID]->start(QThread::NormalPriority);
    connect(threads[threadID], SIGNAL(askForClose(QString)), this, SLOT(onSocketDestroy(QString)));
    connect(threads[threadID], SIGNAL(recvCommand(QString)), this, SLOT(onRecvCommand(QString)));
    connect(musicThread, SIGNAL(statusString(QString)), threads[threadID], SLOT(sendStatus(QString)));
    connect(musicThread, SIGNAL(curPos(double, double)), threads[threadID], SLOT(sendTime(double, double)));
    connect(this, SIGNAL(sendFileList(QStringList)), threads[threadID++], SLOT(updateFileList(QStringList)));

}

void MainWindow::nextSong()
{
    qDebug() << "Next\n";
    currentSongIndex += 1;
    if (currentSongIndex < ui->listWidget_2->count())
    {
        currentFilepath = fileList.at(currentSongIndex);
        //currentFilepath = ui->listWidget_2->item(currentSongIndex)->text();
    }
    else
    {
        currentSongIndex = 0;
        currentFilepath = fileList.at(currentSongIndex);
        //currentFilepath = ui->listWidget_2->item(currentSongIndex)->text();
    }

    emit play(currentFilepath);
}

void MainWindow::onSocketDestroy(QString peerIP)
{
    QListWidgetItem *item;
    int curID;

    for (int i = 0; i < threadID; i++)
        if (ui->listWidget->item(i)->text() == peerIP)
        {
            item = ui->listWidget->takeItem(i);
            curID = i;
            break;
        }

    for (int i = curID; i < threadID; i++)
        threads[i] = threads[i + 1];

    threadID--;

    delete item;
}

void MainWindow::onRecvCommand(QString command)
{
    if (command.contains("PLAY ###"))
    {
        if (currentFilepath == QString(""))
        {
            currentFilepath = fileList.at(0);
            //currentFilepath = ui->listWidget_2->item(0)->text();
            currentSongIndex = 0;
        }
        Bpause = false;

        emit play(currentFilepath);
    }
    else if (command.contains("PAUSE ###"))
    {
        if (Bpause == true)
        {
            emit resume();
            Bpause = false;
        }
        else
        {
            emit pause();
            Bpause = true;
        }
    }
    else if (command.contains("STOP ###"))
    {
        Bpause = false;
        emit stop();
    }
    else if (command.contains("NEXT ###"))
    {
        emit next();
    }
    else if (command.contains("POSITION ###"))
    {
        emit changePos((command.mid(command.lastIndexOf('p') + 1, command.count())).toInt());
    }
    else if (command.contains("CHANGE ###"))
    {
        currentSongIndex = command.mid(command.lastIndexOf('#') + 2, command.count()).toInt();
        currentFilepath = fileList.at(currentSongIndex);
        emit play(currentFilepath);
    }
    else if (command.contains("TIME ### 0"))
        emit checkChange(false);
    else if (command.contains("TIME ### 1"))
        emit checkChange(true);
}

void MainWindow::on_playBtn_clicked()
{
    if (currentFilepath == QString(""))
    {
        currentFilepath = fileList.at(0);
        //currentFilepath = ui->listWidget_2->item(0)->text();
        currentSongIndex = 0;
    }
    Bpause = false;
    emit play(currentFilepath);
}

void MainWindow::on_pauseBtn_clicked()
{
    if (Bpause == true)
    {
        emit resume();
        Bpause = false;
    }
    else
    {
        emit pause();
        Bpause = true;
    }
}

void MainWindow::on_stopBtn_clicked()
{
    emit stop();
    Bpause = false;
}

void MainWindow::on_addBtn_clicked()
{
    QStringList fileNames;
    QFileDialog dialog(this);
    dialog.setDirectory(QDir::homePath());
    dialog.setFileMode(QFileDialog::ExistingFiles);
    dialog.setNameFilter(tr("Music types (*.mp3 *.wav)"));
    if (dialog.exec())
            fileNames = dialog.selectedFiles();

    fileList.append(fileNames);
    fileNames = parseList(fileNames);
    ui->listWidget_2->addItems(fileNames);
    emit sendFileList(fileNames);
}

void MainWindow::on_nextBtn_clicked()
{
    emit next();
}

void MainWindow::on_horizontalSlider_sliderReleased()
{
    emit changePos(ui->horizontalSlider->sliderPosition());
    Bsliderpressed = false;
}

void MainWindow::on_horizontalSlider_sliderPressed()
{
    Bsliderpressed = true;
}

QStringList MainWindow::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 MainWindow::on_listWidget_2_itemClicked(QListWidgetItem *item)
{
    currentSongIndex = ui->listWidget_2->currentRow();
    currentFilepath = fileList.at(currentSongIndex);
    emit play(currentFilepath);
}

void MainWindow::on_pushButton_2_clicked()
{

}

void MainWindow::on_pushButton_3_clicked()
{
    emit openPort((QString) "/dev/ttyUSB0");
}

void MainWindow::on_pushButton_4_clicked()
{
    emit closePort();
}

void MainWindow::on_checkBox_2_toggled(bool checked)
{
    if (checked == true)
        emit checkChange(checked);
    else
        emit checkChange(checked);
}
