#include "formworklist.h"
#include "ui_formworklist.h"
#include "mainwindow.h"

#include "formcalendarview.h"

#include "dialogemergengy.h"

FormWorklist::FormWorklist(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormWorklist)
{
    ui->setupUi(this);

    m_nSearchDurationType = SEARCH_TODAY;

    ui->widgetList->ChangeHeader();

    m_pDialogSearchProgress = new DialogProgress(this);
    m_pDialogSearchProgress->Init(1);
    ui->pushButton_DateEnd->hide();

    //m_pScrollArea = new QScrollArea;
    //m_pScrollArea->setWidget(ui->widgetList);

    MainWindow* pMainWindow = MainWindow::GetMainWindow();
    connect(this, SIGNAL(ChangeMenu(int)), pMainWindow, SLOT(ChangeMenu(int)));

    connect(&m_TimerSearch, SIGNAL(timeout()), this, SLOT(OverTime()));

    m_TimerSearch.setSingleShot(true);

    //m_TimerSearch.setInterval(1000*3);
    //m_TimerSearch.start();


    CreateThreadWorklistSearch();



}

FormWorklist::~FormWorklist()
{
    if(m_pDialogSearchProgress!=NULL)
    {
        delete m_pDialogSearchProgress;
    }

    MainWindow* pMainWindow = MainWindow::GetMainWindow();
    disconnect(this, SIGNAL(ChangeMenu(int)), pMainWindow, SLOT(ChangeMenu(int)));

    delete ui;
}

void FormWorklist::CreateThreadWorklistSearch()
{
    m_pThreadWorklistSearch = new SThreadWorklistSearch;

    connect(m_pThreadWorklistSearch, SIGNAL(worklistUpdateComplete()), this, SLOT(worklistUpdateComplete()));
    connect(m_pThreadWorklistSearch, SIGNAL(worklistError()), this, SLOT(worklistError()));
    connect(m_pThreadWorklistSearch, SIGNAL(SetWorklistProgress(int)), this, SLOT(SetWorklistProgress(int)));

    MainWindow* pMainWindow = MainWindow::GetMainWindow();
    connect(m_pThreadWorklistSearch, SIGNAL(SetDisplayError(QString)), pMainWindow, SLOT(SetDisplayError(QString)));

    m_pThreadWorklistSearch->start();
}

void FormWorklist::TerminateThreadWorklistSearch()
{
    disconnect(m_pThreadWorklistSearch, SIGNAL(worklistUpdateComplete()), this, SLOT(worklistUpdateComplete()));
    disconnect(m_pThreadWorklistSearch, SIGNAL(worklistError()), this, SLOT(worklistError()));
    disconnect(m_pThreadWorklistSearch, SIGNAL(SetWorklistProgress(int)), this, SLOT(SetWorklistProgress(int)));

    //m_pThreadWorklistSearch->terminate();
    m_pThreadWorklistSearch->TerminateThread();
    //m_pThreadWorklistSearch->ExitThread();

    while(m_pThreadWorklistSearch->isRunning()==true)
    {
        usleep(1000*100);
    }

    //SAFE_DELETE(m_pThreadWorklistSearch);
    m_pThreadWorklistSearch->deleteLater();
    usleep(1000*100);
    //m_pThreadWorklistSearch->exit(0);

    m_pThreadWorklistSearch = NULL;
}

void FormWorklist::ClickSearchDateStartEnd()
{
    QDate date = QDate::currentDate();

    CommonData* pCommonData = MainWindow::GetCommonData();
    QDate dateStart = pCommonData->GetDateSearchWorklistStart();
    QDate dateEnd = pCommonData->GetDateSearchWorklistEnd();

    DialogCalendar dlg(this);
    dlg.SetCalendarDate(date.year(), date.month(), 1);
    dlg.SetDateStart(dateStart);
    dlg.SetDateEnd(dateEnd);
    //dlg.SetModeChangeStart();


    MainWindow* pMainWindow = MainWindow::GetMainWindow();
    pMainWindow->StopScreenSaverTimer();

    connect(&dlg, SIGNAL(SetSearchDateUpdate(int)), this, SLOT(SetSearchDateUpdate(int)));

    dlg.exec();
    m_nSearchDurationType = dlg.GetTypeSearchDuration();

    disconnect(&dlg, SIGNAL(SetSearchDateUpdate(int)), this, SLOT(SetSearchDateUpdate(int)));

    pMainWindow->ResetScreenSaverTimer();
    pMainWindow->StartScreenSaverTimer();
}

void FormWorklist::on_pushButton_DateStart_clicked()
{
    WRITE_FUNCTION_LOG();
    ClickSearchDateStartEnd();
}

void FormWorklist::on_pushButton_DateEnd_clicked()
{
    WRITE_FUNCTION_LOG();
    ClickSearchDateStartEnd();
}

void FormWorklist::SetSearchDateUpdate(int nTypeSearchDuration)
{
    WRITE_FUNCTION_LOG();
    CommonData* pCommonData = MainWindow::GetCommonData();
    //QDate dateStart = pMainWindow->GetDateSearchWorklistStart();// FormCalendarView::GetDateStart();
    //QDate dateEnd = pMainWindow->GetDateSearchWorklistEnd();// FormCalendarView::GetDateEnd();
    QDate dateStart = FormCalendarView::GetDateStart();
    QDate dateEnd = FormCalendarView::GetDateEnd();
    QDate dateToday = QDate::currentDate();

    m_nSearchDurationType = nTypeSearchDuration;

    pCommonData->GetSearchDateStartEnd(m_nSearchDurationType, dateStart, dateEnd);
    pCommonData->SetDateSearchWorklistStart(dateStart);
    pCommonData->SetDateSearchWorklistEnd(dateEnd);

    QString strDateStart;
    QString strDateEnd;

    int nStartYear = dateStart.year();
    int nStartMonth = dateStart.month();
    int nStartDay = dateStart.day();

    int nEndYear = dateEnd.year();
    int nEndMonth = dateEnd.month();
    int nEndDay = dateEnd.day();

    strDateStart = QString("%1/%2/%3").arg(QString::number(nStartYear).rightJustified(4, '0')).arg(QString::number(nStartMonth).rightJustified(2, '0')).arg(QString::number(nStartDay).rightJustified(2, '0'));

    strDateEnd = QString("%1/%2/%3").arg(QString::number(nEndYear).rightJustified(4, '0')).arg(QString::number(nEndMonth).rightJustified(2, '0')).arg(QString::number(nEndDay).rightJustified(2, '0'));

    if(m_nSearchDurationType==SEARCH_TODAY)
    {
        ui->label_DateStart->setText("Today");
    }
    else
    {
        QString strSearchDate = QString("%1 ~ %2").arg(strDateStart).arg(strDateEnd);
        ui->label_DateStart->setText(strSearchDate);
        ui->pushButton_DateStart->update();
        //ui->label_DateEnd->setText(strSearchDate);
    }

    /*
    if(dateToday==dateStart)
    {
        ui->label_DateStart->setText("Today");
    }
    else
    {

    }

    if(dateToday==dateEnd)
    {
        ui->label_DateEnd->setText("Today");
    }
    else
    {
        ui->label_DateEnd->setText(strDateEnd);
    }
    */


    SEARCH_ITEM* pSearchItem = pCommonData->GetSearchItemWorklist();
    pSearchItem->m_strStudyDate = QString("%1-%2").arg(strDateStart).arg(strDateEnd);

    //ui->pushButton_DateStart->setText(strDateStart);
    //ui->pushButton_DateEnd->setText(strDateEnd);

}

void FormWorklist::Init()
{
    WRITE_FUNCTION_LOG();
    ui->widgetList->Clear();
    ui->widgetList->ChangeHeader();
    ui->widgetList->Init();
    ui->widgetList->UpdateList();
}

void FormWorklist::on_pushButton_Execution_clicked()
{
    WRITE_FUNCTION_LOG();
    Exit();
}


void FormWorklist::resizeEvent(QResizeEvent *event)
{
    WRITE_FUNCTION_LOG();
    int nDisplayType = MainWindow::GetCommonData()->GetDisplayType();

    int nFontSize = 22;
    if(nDisplayType==SDISPLAY_1280X1024)
    {
        nFontSize = 16;

        ui->frame_PatientID->setGeometry(20, 28, 156, 32);
        ui->frame_PatientName->setGeometry(195, 28, 156, 32);
        ui->pushButton_DateStart->setGeometry(376, 28, 278, 32);
        ui->pushButton_DateEnd->setGeometry(580, 28, 178, 32);

        ui->plainTextEdit_PatientID->setGeometry(30, 31, 140, 40);
        ui->plainTextEdit_PatientName->setGeometry(205, 31, 140, 40);

        ui->label_DateStart->setGeometry(18, 0, 260, 36);
        ui->label_DateEnd->setGeometry(18, 0, 160, 36);

        ui->widgetList->setGeometry(20, 91, 1150, 665-15);

        ui->pushButton_Execution->setGeometry(1024, 91+665+30, 145, 45);

        ui->pushButton_Emergency->setGeometry(20, 91+665+30, 145, 45);

        ui->pushButton->setGeometry(1025, 21, 145, 45);
    }
    else if(nDisplayType==SDISPLAY_1920X1080)
    {
        ui->frame_PatientID->setGeometry(30, 34, 195, 40);
        ui->frame_PatientName->setGeometry(250, 34, 195, 40);
        ui->pushButton_DateStart->setGeometry(477, 34, 268, 40);
        ui->pushButton_DateEnd->setGeometry(770, 34, 268, 40);

        ui->plainTextEdit_PatientID->setGeometry(40, 40, 175, 50);
        ui->plainTextEdit_PatientName->setGeometry(260, 40, 175, 50);

        ui->label_DateStart->setGeometry(20, 0, 201, 40);
        ui->label_DateEnd->setGeometry(20, 0, 201, 40);

        ui->widgetList->setGeometry(30, 108, 1750, 640);

        ui->pushButton_Execution->setGeometry(1598, 780, 180, 56);

        ui->pushButton->setGeometry(1600, 24, 180, 56);
    }

    QString strPushButton = QString(
    "QPushButton \
    { \
           background: #153B44; \
           font-family: 'Roboto'; \
           font-size: %1px; \
           font-weight: bold; \
           border-radius: 8px; \
           color: white; \
    } \
     \
    QPushButton:pressed \
    { \
           background: #1B4C54; \
    }").arg(nFontSize);

    ui->pushButton->setStyleSheet(strPushButton);



    QString strPushButton_Execution = QString(
    "QPushButton \
    { \
           background: #FFFFFF; \
           font-family: 'Roboto'; \
           font-size: %1px; \
           font-weight: bold; \
           border-radius: 8px; \
           color: black; \
    } \
     \
    QPushButton:pressed \
    { \
           background: #D8D8D8; \
    }").arg(nFontSize);

    ui->pushButton_Execution->setStyleSheet(strPushButton_Execution);

    ui->pushButton_Execution->hide();
}

#include <QProcess>

void FormWorklist::on_pushButton_clicked()
{
    WRITE_FUNCTION_LOG();
    //QString strExec = "smplayer /home/birdhead/Videos/1.mp4";
    //strExec = "nautilus /home/birdhead/Videos";

    //QProcess::execute(strExec);

    //return;

    CommonData* pCommonData = MainWindow::GetCommonData();

    QDate dateStart = pCommonData->GetDateSearchWorklistStart();
    QDate dateEnd = pCommonData->GetDateSearchWorklistEnd();
    pCommonData->GetSearchDateStartEnd(m_nSearchDurationType, dateStart, dateEnd);
    pCommonData->SetDateSearchWorklistStart(dateStart);
    pCommonData->SetDateSearchWorklistEnd(dateEnd);

    vector<WorklistResponseData>* pListWorklist = pCommonData->GetWorklistData();
    pListWorklist->clear();
    pCommonData->ReleaseWorklistData();

    ui->widgetList->Clear();
    ui->widgetList->Init();


    //SThreadSendDICOM* pThread = pCommonData->GetThreadSendDICOM();

    m_pDialogSearchProgress->Init();

    //pThread->SearchWorklist();
    //m_TimerSearch.setSingleShot(true);
    m_TimerSearch.start(1000*20);
    m_pThreadWorklistSearch->SearchWorklist();
    m_pDialogSearchProgress->exec();
    //m_pDialogSearchProgress->show();
}

void FormWorklist::worklistUpdateComplete()
{
    WRITE_FUNCTION_LOG();
    m_TimerSearch.stop();
    ui->widgetList->UpdateList();
    m_pDialogSearchProgress->OnWorklistComplete();
}

void FormWorklist::worklistError()
{
    WRITE_FUNCTION_LOG();

    //CommonData::RestartNetworkManager();


    m_TimerSearch.stop();
    ui->widgetList->UpdateList();
    m_pDialogSearchProgress->OnWorklistError();


}

void FormWorklist::SetWorklistProgress(int nValue)
{
    if(nValue<0)
    {
        worklistError();
        return;
    }
    m_pDialogSearchProgress->DisplayInfo(nValue);
    //m_TimerSearch.stop();
}

void FormWorklist::on_plainTextEdit_PatientName_textChanged()
{
    WRITE_FUNCTION_LOG();
    CommonData* pCommonData = MainWindow::GetCommonData();
    SEARCH_ITEM* pSearchItem = pCommonData->GetSearchItemWorklist();

    QString strPatientName = ui->plainTextEdit_PatientName->toPlainText();
    pSearchItem->m_strPatientName = strPatientName;
}

void FormWorklist::on_plainTextEdit_PatientID_textChanged()
{
    WRITE_FUNCTION_LOG();
    CommonData* pCommonData = MainWindow::GetCommonData();
    SEARCH_ITEM* pSearchItem = pCommonData->GetSearchItemWorklist();

    QString strPatientID = ui->plainTextEdit_PatientID->toPlainText();
    pSearchItem->m_strPatientID = strPatientID;
}

void FormWorklist::on_pushButton_Emergency_clicked()
{
    /*
    MainWindow* pMainWindow = MainWindow::GetMainWindow();
    pMainWindow->Exit();
    return;
    */
    WRITE_FUNCTION_LOG();
    DialogEmergengy dlg(this);

    MainWindow* pMainWindow = MainWindow::GetMainWindow();
    pMainWindow->StopScreenSaverTimer();

    if(dlg.exec()==QDialog::Accepted)
    {
        CommonData* pCommonData = MainWindow::GetCommonData();
        ACQUISITION_INFO* pAcquisitionInfo = pCommonData->GetAcquisitionInfo();

        QDateTime dt = QDateTime::currentDateTime();
        int nYear = dt.date().year();
        int nMonth = dt.date().month();
        int nDay = dt.date().day();
        int nHour = dt.time().hour();
        int nMinute = dt.time().minute();
        int nSecond = dt.time().second();

        QString strPatientID;
        QString strPatientName;
        QString strPatientBirthDate;
        QString strPatientSex;

        QString strModality;

        strModality = pCommonData->GetModality();

        strPatientID = dlg.GetPatientID();
        strPatientName = dlg.GetPatientName();
        strPatientBirthDate = dlg.GetPatientBirthDate();
        strPatientSex = dlg.GetPatientSex();

        if(strPatientSex=="Male")
        {
            strPatientSex = "M";
        }
        else if(strPatientSex=="Female")
        {
            strPatientSex = "F";
        }
        else if(strPatientSex=="Other")
        {
            strPatientSex = "O";
        }

        if(strPatientBirthDate.size()<8)
        {
            strPatientBirthDate = QString("%1/%2/%3").arg(QString::number(nYear).rightJustified(4, '0')).arg(QString::number(nMonth).rightJustified(2, '0'))
                    .arg(QString::number(nDay).rightJustified(2, '0'));
        }

        strPatientBirthDate.remove('/');
        strPatientBirthDate.remove('.');

        if(strPatientID.size()>0 && strPatientName.size()>0 && strPatientSex.size()>0 && strPatientBirthDate.size()==8)
        {
            pAcquisitionInfo->Clear();
            pAcquisitionInfo->GetPatientInfo()->strPatientID = strPatientID.toStdString().c_str();
            pAcquisitionInfo->GetPatientInfo()->strPatientName = strPatientName.toStdString().c_str();
            pAcquisitionInfo->GetStudyInfo()->strStudyInstanceUID = (QString("1.1.22.33.%1.1%2%3.1%4").arg(pAcquisitionInfo->GetPatientInfo()->strPatientID).arg(QString::number(nHour)).arg(QString::number(nMinute)).arg(QString::number(nSecond))).toStdString().c_str();
            pAcquisitionInfo->GetStudyInfo()->strStudyDescription = "Emergengy Desc.";
            pAcquisitionInfo->GetSeriesInfo()->strSeriesDescription = "Emergency Desc.";
            pAcquisitionInfo->GetSeriesInfo()->strOperatorsName = "";

            pAcquisitionInfo->GetPatientInfo()->strPatientSex = strPatientSex.toStdString().c_str();
            pAcquisitionInfo->GetPatientInfo()->strPatientWeight = "";
            pAcquisitionInfo->GetPatientInfo()->strPatientBirthDate = strPatientBirthDate.toStdString().c_str();

            pAcquisitionInfo->GetSeriesInfo()->strModality = strModality.toStdString().c_str();

            pCommonData->ReleaseAcquisitionInfo();

            ChangeMenu(SMENU_CAPTURE);
        }
        else
        {
            pCommonData->ReleaseAcquisitionInfo();
        }


    }

    pMainWindow->ResetScreenSaverTimer();
    pMainWindow->StartScreenSaverTimer();
}

void FormWorklist::keyReleaseEvent(QKeyEvent *event)
{
    WRITE_FUNCTION_LOG();
    int nKey = event->key();

    SThreadImageSave* pThread = MainWindow::GetCommonData()->GetThreadCaptureImage();

    if(nKey==Qt::Key_F10)
    {
        pThread->MissCapture();
    }
    else if(nKey==Qt::Key_F11)
    {
        pThread->MissCapture();
    }

}



void FormWorklist::OverTime()
{
    TerminateThreadWorklistSearch();

    CommonData::RestartNetworkManager();

    usleep(1000*100);
    CreateThreadWorklistSearch();

    m_TimerSearch.stop();
    ui->widgetList->UpdateList();
    m_pDialogSearchProgress->DisplayInfo(-12);
    //m_pDialogSearchProgress->exec();


}


void FormWorklist::ErrorPatientInfo()
{
    ui->widgetList->SetExecMenu(false);
}



