#include "qremote_playback.h"
#include <qpalette>

const QString icon_play = ":/multi_ipnc_demo/Resources/btn_player_play.png";
const QString icon_pause = ":/multi_ipnc_demo/Resources/btn_player_pause.png";

QRemotePlayback::QRemotePlayback(QWidget *parent)
    : QWidget(parent),
      paused_(false),
      audio_(false),
      file_type_(0)
{
    ui_.setupUi(this);

    ClearSearchResult();

    vod_play_channel_.dev_id = -1;
    vod_play_channel_.channel = NS_VOD_PLAY_CHANNEL;
    vod_play_channel_.stream = 0;

    vod_download_channel_.dev_id = -1;
    vod_download_channel_.channel = NS_VOD_DOWNLOAD_CHANNEL;
    vod_download_channel_.stream = 0;

    params_.draw_wnd = ui_.wdtPlaybackPanel->winId();

    QPalette palette;
    palette.setColor(QPalette::Background, QColor(0,0,0));
    ui_.wdtPlaybackPanel->setPalette(palette);

    QObject::connect(ui_.btnPlayerPlay, SIGNAL(clicked()), this, SLOT(OnClickPlay()));
    QObject::connect(ui_.btnPlayerFast, SIGNAL(clicked()), this, SLOT(OnClickFast()));
    QObject::connect(ui_.btnPlayerSlow, SIGNAL(clicked()), this, SLOT(OnClickSlow()));
    QObject::connect(ui_.btnPlayerStep, SIGNAL(clicked()), this, SLOT(OnClickStep()));
    QObject::connect(ui_.btnPlayerAudio, SIGNAL(clicked()), this, SLOT(OnClickAudio()));
    QObject::connect(ui_.btnPlayerStop, SIGNAL(clicked()), this, SLOT(OnClickStop()));

    QObject::connect(ui_.btnSearchFile, SIGNAL(clicked()), this, SLOT(SlotOnSearchFiles()));
    QObject::connect(ui_.ltwFileList, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(SlotOnFileListDblClicked(QListWidgetItem *)));

    QObject::connect(ui_.hsPlayerProgress, SIGNAL(sliderReleased()), this, SLOT(OnChangeProgress()));
    
    QObject::connect(ui_.btnGoToPage, SIGNAL(clicked()), this, SLOT(GoToPage()));

    timer_get_progress_ = new QTimer(this);
    QObject::connect(timer_get_progress_,SIGNAL(timeout()),this,SLOT(OnTimerGetProgress()));
    timer_get_progress_->setSingleShot(false);

    OnClickStop();
}

QRemotePlayback::~QRemotePlayback()
{

}

void QRemotePlayback::SlotOnSearchFiles()
{
    DoSearch(0,15);
}

void QRemotePlayback::show()
{
    QDateTime begin(QDate::currentDate(),QTime(0,0));
    QDateTime end(QDate::currentDate(),QTime::currentTime());
    ui_.dtFileBegin->setDateTime(begin);
    ui_.dtFileEnd->setDateTime(end);

    ClearSearchResult();

    QWidget::show();
}

void QRemotePlayback::DoSearch( int begin,int count )
{
    ui_.ltwFileList->clear();
    memset(&list_,0,sizeof(list_));
    current_play_index_ = -1;
    if (vod_play_channel_.dev_id >= 0)
    {
        NsstChannel ch;
        ch.dev_id = vod_play_channel_.dev_id;
        ch.channel = ui_.cbbSearchChannel->currentIndex();
        ch.stream = 0;

        condition_.begin_index = begin ;
        condition_.page_count = count ;
        condition_.file_type = ui_.cbbMediaType->currentIndex();
        condition_.event_type = ui_.cbbFileType->currentIndex();
        condition_.begin_time = ui_.dtFileBegin->dateTime().toTime_t();
        condition_.end_time = ui_.dtFileEnd->dateTime().toTime_t();
        NSSTSearchFile(&ch,&condition_);
    }
}

void QRemotePlayback::OnSearchResult( NsstMediaFileList* filelist )
{
    memcpy(&list_,filelist,sizeof(list_));
    for (unsigned i = 0;i < filelist->current_count;++i)
    {
        NsstMediaFileItem* p = &filelist->item[i];
        QListWidgetItem* item = NULL;
        if (filelist->file_type == 0)
        {
            item = new QListWidgetItem(QIcon(":/multi_ipnc_demo/Resources/icon_mp4.png"),p->path);
        }
        else
        {
            item = new QListWidgetItem(QIcon(":/multi_ipnc_demo/Resources/icon_jpg.png"),p->path);
        }
        file_type_ = filelist->file_type;
        
        QString tips;
        QDateTime dt1 = QDateTime::fromTime_t(p->begin_time);
        QDateTime dt2 = QDateTime::fromTime_t(p->end_time);
        tips.sprintf("From: %s\nTo: %s\nSize: %d",
            dt1.toString("MM/dd/yyyy hh:mm:ss").toUtf8().data(),
            dt2.toString("MM/dd/yyyy hh:mm:ss").toUtf8().data(),
            p->size);
        item->setToolTip(tips);
        ui_.ltwFileList->addItem(item);
    }

    ui_.lblFileTotal->setText(QString("/")+QString::number(filelist->total));
}

void QRemotePlayback::SlotOnFileListDblClicked( QListWidgetItem *item )
{   
    if (item && vod_play_channel_.dev_id >= 0)
    {
        current_play_index_ = ui_.ltwFileList->currentRow();
        if (current_play_index_ < list_.current_count )
        {
            if (file_type_ == 0)
            {
                OnClickStop();
                params_.width = ui_.wdtPlaybackPanel->width();
                params_.height = ui_.wdtPlaybackPanel->height();
                NSSTStartRecordTransport(&vod_play_channel_,
                    &params_,list_.item[current_play_index_].path);

                ui_.btnPlayerPlay->setEnabled(true);
                ui_.btnPlayerPlay->setIcon(QIcon(icon_pause));

                ui_.hsPlayerProgress->setEnabled(true);

                timer_get_progress_->start(1000);

                paused_ = false;
            }
            else
            {
                NsstChannel ch;
                ch.dev_id = vod_play_channel_.dev_id;
                ch.channel = 0;
                ch.stream = 0;
                QString local_path = QCoreApplication::applicationDirPath();
                local_path.replace('/','\\');
                local_path.append("\\Download\\");
                local_path.append(list_.item[current_play_index_].path);

                ui_.edtTips->setText("");

                NSSTStartPictureDownload(&ch,
                    list_.item[current_play_index_].path,
                    local_path.toUtf8().data(),
                    list_.item[current_play_index_].size);
                ui_.pbDownloadJpeg->setValue(0);
            }
        }
    }
}

void QRemotePlayback::OnClickPlay()
{
    if (paused_)
    {
        ui_.btnPlayerPlay->setIcon(QIcon(icon_pause));
        NSSTMediaResume(&vod_play_channel_);
    }
    else
    {
        ui_.btnPlayerPlay->setIcon(QIcon(icon_play));
        NSSTMediaPause(&vod_play_channel_);
    }
    paused_ = !paused_;
}

void QRemotePlayback::OnClickFast()
{
    if (vod_play_channel_.dev_id >= 0)
    {
        NSSTMediaSetSpeed(&vod_play_channel_,2);
    }
}

void QRemotePlayback::OnClickSlow()
{
    if (vod_play_channel_.dev_id >= 0)
    {
        NSSTMediaSetSpeed(&vod_play_channel_,-2);
    }
}

void QRemotePlayback::OnClickStep()
{
    if (vod_play_channel_.dev_id >= 0)
    {
        NSSTMediaStep(&vod_play_channel_);
    }
}

void QRemotePlayback::OnClickAudio()
{
    if (vod_play_channel_.dev_id >= 0)
    {
        if (audio_)
        {
            NSSTPlayAudio(&vod_play_channel_);
        }
        else
        {
            NSSTCloseAudio(&vod_play_channel_);
        }
        audio_ = !audio_;
    }
}

void QRemotePlayback::OnClickStop()
{
    if (vod_play_channel_.dev_id >= 0)
    {
        NSSTStopTransport(&vod_play_channel_);
    }
    ui_.btnPlayerPlay->setIcon(QIcon(icon_play));
    ui_.btnPlayerPlay->setEnabled(false);

    ui_.hsPlayerProgress->setEnabled(false);

    ui_.hsPlayerProgress->blockSignals(true);
    ui_.hsPlayerProgress->setValue(0);
    ui_.hsPlayerProgress->blockSignals(false);

    timer_get_progress_->stop();

    ui_.wdtPlaybackPanel->update();

    ui_.lblPlayerTime->setText("00:00:00/00:00:00");

    paused_ = false;
}

void QRemotePlayback::id( DEVICE_ID val )
{
    vod_play_channel_.dev_id = val;
    vod_download_channel_.dev_id = val;
}

void QRemotePlayback::OnSDKMessage( int event_type,NsstEventCommonParam* event_param )
{
    switch (event_type)
    {
    case NSSTEV_MEDIA_CONNECTED:
        {
            break;
        }
    case NSSTEV_MEDIA_RECONNECTING:
        {
            break;
        }
    case NSSTEV_MEDIA_ERROR:
        {
            OnClickStop();
            break;
        }
    case NSSTEV_MEDIA_EOF:
        {
            OnClickStop();
            break;
        }
    default:
    	break;
    }
}

void QRemotePlayback::closeEvent( QCloseEvent * ev)
{
    OnClickStop();
}

void QRemotePlayback::ClearSearchResult()
{
    memset(&list_,0,sizeof(list_));
    current_play_index_ = -1;
    ui_.ltwFileList->clear();
}

void QRemotePlayback::OnTimerGetProgress()
{
    __int64 total_time = NSSTMediaGetTotalTime(&vod_play_channel_);
    if (total_time <= 0)
    {
        return;
    }
    __int64 current_time = NSSTMediaGetCurrentTime(&vod_play_channel_);
    __int64 val = current_time * (__int64)1000 / total_time;
    
    QTime tt;
    tt = tt.addMSecs(total_time);
    QTime ct;
    ct = ct.addMSecs(current_time);
    ui_.lblPlayerTime->setText(ct.toString()+QString("/")+tt.toString());

    ui_.hsPlayerProgress->blockSignals(true);
    ui_.hsPlayerProgress->setValue((int)val);
    ui_.hsPlayerProgress->blockSignals(false);
}

void QRemotePlayback::OnChangeProgress()
{
    int permillage = ui_.hsPlayerProgress->value();
    NSSTMediaSeekPos(&vod_play_channel_,permillage);
}

void QRemotePlayback::GoToPage()
{
    int begin = (ui_.spinSelPage->value() - 1) * condition_.page_count;
    DoSearch(begin,15);
}

void QRemotePlayback::OnGetJPEGProgress(int speed,int current_size,int total_size)
{
    if (total_size > 0)
    {
        ui_.pbDownloadJpeg->setValue(current_size * 100 / total_size);
    }
}

void QRemotePlayback::OnJPEGResult( int error_code )
{
    if (error_code == 0)
    {
        ui_.edtTips->setText("Download success!");
    }
    else
    {
        ui_.edtTips->setText("Download failed!");
    }
}
