#include "formviewer.h"
#include "ui_formviewer.h"


#include <QThread>
#include <QWheelEvent>

#include "mainwindow.h"

#include "dialogprogress.h"

#include "SDCMSendImpl.h"
#include "cscallbacksendprogress.h"

#include "SDCMImage.h"

#include <QFileInfo>
#include <QDirIterator>


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

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

    m_nIndexCurrent = 0;
    m_nTotalImageCount = 0;

    m_pSlideBarVertical = ui->verticalScrollBar;

    m_pDialogSendProgress = new DialogProgress(this);

    ui->verticalScrollBar->SetSlideType(SSlideBar::SLIDE_VERTICAL);
    ui->verticalScrollBar->setRange(0, 299);

    connect(ui->verticalScrollBar, SIGNAL(valueChanged(int)), this, SLOT(valueChangedScrollBarVertical(int)));
    //connect(this, SIGNAL(SetSlideValue(int)), ui->verticalScrollBar, SLOT(setValue(int)));
    connect(ui->verticalScrollBar, SIGNAL(actionTriggered(int)), this, SLOT(actionTriggered(int)));
    connect(ui->verticalScrollBar, SIGNAL(SingleDown()), this, SLOT(SingleDown()));
    connect(ui->verticalScrollBar, SIGNAL(SingleUp()), this, SLOT(SingleUp()));





    int i = 0;
    for(i=0 ; i<9 ; i++)
    {
        FormImageSelect* pForm = new FormImageSelect(this);
        pForm->SetIndexViewer(i);
        pForm->hide();

        m_ListFormImageSelect.push_back(pForm);
    }

    //ChangeViewMode(0);


}

FormViewer::~FormViewer()
{
    CommonData* pCommonData = MainWindow::GetCommonData();
    MainWindow* pMainWindow = MainWindow::GetMainWindow();
    SThreadImageSave* pThreadImage = pCommonData->GetThreadCaptureImage();

    disconnect(pThreadImage, SIGNAL(ImageLoadComplete()), this, SLOT(ImageLoadComplete()));

    disconnect(this, SIGNAL(ExitViewer()), pMainWindow, SLOT(ExitViewer()));
    disconnect(this, SIGNAL(ChangeMenu(int)), pMainWindow, SLOT(ChangeMenu(int)));
    disconnect(this, SIGNAL(BackupNetworkShareFolder(QString)), pMainWindow, SLOT(BackupNetworkShareFolder(QString)));


    disconnect(ui->verticalScrollBar, SIGNAL(valueChanged(int)), this, SLOT(valueChangedScrollBarVertical(int)));
    //disconnect(this, SIGNAL(SetSlideValue(int)), ui->verticalScrollBar, SLOT(setValue(int)));
    disconnect(ui->verticalScrollBar, SIGNAL(actionTriggered(int)), this, SLOT(actionTriggered(int)));
    disconnect(ui->verticalScrollBar, SIGNAL(SingleDown()), this, SLOT(SingleDown()));
    disconnect(ui->verticalScrollBar, SIGNAL(SingleUp()), this, SLOT(SingleUp()));

    if(m_pDialogSendProgress!=NULL)
    {
        delete m_pDialogSendProgress;
    }

    delete ui;
}

void FormViewer::on_comboBox_ViewerMode_currentIndexChanged(int index)
{
    ChangeViewMode(index);
}


void FormViewer::ChangeViewMode(int nMode)
{
    int nIndex = 0;
    int nRow = ui->gridLayout_Viewer->rowCount();
    int nColumn = ui->gridLayout_Viewer->columnCount();

    int i=0;
    int j=0;

    if(m_nMode!=nMode)
    {
        m_nIndexCurrent = 0;



        for(i=0 ; i<nRow ; i++)
        {
            for(j=0 ; j<nColumn ; j++)
            {
                FormImageSelect* pForm = m_ListFormImageSelect[nIndex];
                nIndex++;

                pForm->hide();

                ui->gridLayout_Viewer->removeWidget(pForm);
            }
        }

        nIndex = 0;

        nRow = 1;
        nColumn = 1;

        if(nMode==0)
        {
            nRow = 1;
            nColumn = 1;
        }
        else if(nMode==1)
        {
            nRow = 2;
            nColumn = 2;
        }
        else if(nMode==2)
        {
            nRow = 3;
            nColumn = 3;
        }

        for(i=0 ; i<nRow ; i++)
        {
            for(j=0 ; j<nColumn ; j++)
            {
                FormImageSelect* pForm = m_ListFormImageSelect[nIndex];
                nIndex++;

                ui->gridLayout_Viewer->addWidget(pForm, i, j);
                pForm->show();
                pForm->Init();

            }
        }
    }

    m_nMode = nMode;

    nIndex = 0;

    //CommonData* pCommonData = MainWindow::GetCommonData();
    //vector<ImageSelect*>* pListHistoryImage = pCommonData->GetListHistoryImage();

    int nTotalImage = 0;
    //for(i=0 ; i<pListHistoryImage->size() ; i++)
    for(i=0 ; i<m_ListImageSelect.size() ; i++)
    {
        //ImageSelect* pImageSelect = (*pListHistoryImage)[i];
        ImageSelect* pImageSelect = m_ListImageSelect[i];
        if(pImageSelect->m_bDelete==false)
        {
            nTotalImage++;
        }
    }

    //m_nTotalImageCount = nTotalImage;

    for(i=0 ; i<nRow ; i++)
    {
        for(j=0 ; j<nColumn ; j++)
        {
            FormImageSelect* pForm = m_ListFormImageSelect[nIndex];
            //ImageSelect* pImageSelect = m_ListImage[nIndex];
            ImageSelect* pImageSelect = NULL;

            if(nTotalImage > nIndex)
            {
                int k=0;
                int nTestIndex = 0;
                //for(k=0 ; k<pListHistoryImage->size() ; k++)
                for(k=0 ; k<m_ListImageSelect.size() ; k++)
                {
                    //ImageSelect* pTmpImage = (*pListHistoryImage)[k];
                    ImageSelect* pTmpImage = m_ListImageSelect[k];
                    if(pTmpImage->m_bDelete==false)
                    {
                        if(nTestIndex==nIndex)
                        {
                            pImageSelect = pTmpImage;
                            break;
                        }
                        nTestIndex++;
                    }
                    //pImageSelect = (*pListHistoryImage)[nIndex];
                }

            }
            pForm->SetImageSelect(pImageSelect);


            pForm->update();

            nIndex++;



        }
    }

    int nItem = 20;
    int nIndexCurrent = m_nIndexCurrent;

    //nItem = pListHistoryImage->size();
    nItem = m_nTotalImageCount;

    float fMaxRange = 299;

    int nPageDisplay = 0;
    int nPageTotal = 0;
    int nItemPerPage = 1;

    switch(m_nMode)
    {
    case 0:
        nItemPerPage = 1;
        break;
    case 1:
        nItemPerPage = 4;
        break;
    case 2:
        nItemPerPage = 9;
        break;
    }

    //nIndexCurrent += nItemPerPage;
    //nPageTotal = ((nItem-1) / nItemPerPage) + 1;
    //nPageDisplay = nIndexCurrent / nItemPerPage;

    nPageTotal = (nItem-1) / nItemPerPage;
    nPageDisplay = nIndexCurrent + 1;

    nPageTotal = nPageTotal + 1;



    if(nPageTotal<=1)
    {
        ui->frame_verticalScrollBar->hide();
        m_pSlideBarVertical->hide();
    }
    else
    {
        if(m_pSlideBarVertical!=NULL)
        {
            m_pSlideBarVertical->setValue(0);
        }

        ui->frame_verticalScrollBar->show();
        m_pSlideBarVertical->show();
    }

    update();

    ui->comboBox_ViewerMode->setCurrentIndex(nMode);

    //QString strIndexPage = QString("Page Index: %1/%2").arg(nPageDisplay+1).arg(nPageTotal);
    QString strIndexPage = QString("Page Index: %1/%2").arg(nPageDisplay).arg(nPageTotal);
    ui->info_DisplayIndex->setText(strIndexPage);
}


void FormViewer::SingleUp()
{
    //CommonData* pCommonData = MainWindow::GetCommonData();
    //vector<ImageSelect*>* pListHistoryImage = pCommonData->GetListHistoryImage();
    int nItem = 20;
    int nIndexCurrent = m_nIndexCurrent;

    //nItem = pListHistoryImage->size();
    nItem = m_nTotalImageCount;

    float fMaxRange = 300;

    int nPageDisplay = 0;
    int nPageTotal = 0;
    int nItemPerPage = 1;

    switch(m_nMode)
    {
    case 0:
        nItemPerPage = 1;
        break;
    case 1:
        nItemPerPage = 4;
        break;
    case 2:
        nItemPerPage = 9;
        break;
    }

    nIndexCurrent -= nItemPerPage;
    nPageTotal = ((nItem-1) / nItemPerPage) + 1;
    nPageDisplay = nIndexCurrent / nItemPerPage;

    if(nPageTotal<=1)
    {
        return;
    }

    if(nPageDisplay < 0)
    {
        nPageDisplay = 0;
    }
    nIndexCurrent = nPageDisplay * nItemPerPage;

    if(nIndexCurrent!=m_nIndexCurrent)
    {
        int nCurrentPos;
        nCurrentPos = (int)(((float)nPageDisplay / (float)(nPageTotal-1)) * fMaxRange + 0.5f);
        //qDebug() << "PageDisplay: " << nPageDisplay << " PageTotal: " << nPageTotal << " nCurrentPos: " << nCurrentPos;
        m_pSlideBarVertical->setValue(nCurrentPos);
    }

    QString strIndexPage = QString("Page Index: %1/%2").arg(nPageDisplay+1).arg(nPageTotal);
    ui->info_DisplayIndex->setText(strIndexPage);

    QString strInfoStoage = QString("IMG: %1").arg(m_nTotalImageCount);
    ui->info_Storage->setText(strInfoStoage);
}

void FormViewer::SingleDown()
{
    //CommonData* pCommonData = MainWindow::GetCommonData();
    //vector<ImageSelect*>* pListHistoryImage = pCommonData->GetListHistoryImage();
    int nItem = 20;
    int nIndexCurrent = m_nIndexCurrent;

    //nItem = pListHistoryImage->size();
    nItem = m_nTotalImageCount;

    float fMaxRange = 299;

    int nPageDisplay = 0;
    int nPageTotal = 0;
    int nItemPerPage = 1;

    switch(m_nMode)
    {
    case 0:
        nItemPerPage = 1;
        break;
    case 1:
        nItemPerPage = 4;
        break;
    case 2:
        nItemPerPage = 9;
        break;
    }

    nIndexCurrent += nItemPerPage;
    nPageTotal = ((nItem-1) / nItemPerPage) + 1;
    nPageDisplay = nIndexCurrent / nItemPerPage;

    if(nPageTotal<=1)
    {
        return;
    }

    if(nPageDisplay >= nPageTotal)
    {
        nPageDisplay = nPageTotal - 1;
    }
    nIndexCurrent = nPageDisplay * nItemPerPage;

    if(nIndexCurrent!=m_nIndexCurrent)
    {
        int nCurrentPos;
        nCurrentPos = (int)( (((float)nPageDisplay / (float)(nPageTotal-1)) * fMaxRange) + 0.5f);
        //qDebug() << "PageDisplay: " << nPageDisplay << " PageTotal: " << nPageTotal << " nCurrentPos: " << nCurrentPos;
        m_pSlideBarVertical->setValue(nCurrentPos);
    }

    QString strIndexPage = QString("Page Index: %1/%2").arg(nPageDisplay+1).arg(nPageTotal);
    ui->info_DisplayIndex->setText(strIndexPage);

    QString strInfoStoage = QString("IMG: %1").arg(m_nTotalImageCount);
    ui->info_Storage->setText(strInfoStoage);

}

void FormViewer::valueChangedScrollBarVertical(int value)
{
    //CommonData* pCommonData = MainWindow::GetCommonData();
    //vector<ImageSelect*>* pListHistoryImage = pCommonData->GetListHistoryImage();

    //int nItem = pListHistoryImage->size();
    int nItem = m_nTotalImageCount;

    float fMaxItem = nItem;
    float fMaxRange = 299;
    int nItemIndex = (((float)value/fMaxRange) * fMaxItem + 0.5f);

    int nPageDisplay = 0;
    int nPageTotal = 0;
    int nItemPerPage = 1;



    switch(m_nMode)
    {
    case 0:
        nItemPerPage = 1;
        break;
    case 1:
        nItemPerPage = 4;
        break;
    case 2:
        nItemPerPage = 9;
        break;
    }

    nPageTotal = ((nItem-1) / nItemPerPage) + 1;
    nPageDisplay = ( ((float)value / fMaxRange) * (nPageTotal-1) + 0.5f );

    //nItemIndex += nItemPerPage;
    //nPageDisplay = nItemIndex / nItemPerPage;

    if(nPageTotal<=1)
    {
        return;
    }

    if(nPageDisplay >= nPageTotal)
    {
        nPageDisplay = nPageTotal-1;
    }

    nItemIndex = nPageDisplay * nItemPerPage;

    m_nCurrentPos = value;

    if(m_nIndexCurrent!=nItemIndex)
    {
        m_nIndexCurrent = nItemIndex;
        UpdateViewer();

        QString strIndexPage = QString("Page Index: %1/%2").arg(nPageDisplay+1).arg(nPageTotal);
        ui->info_DisplayIndex->setText(strIndexPage);
    }


}


void FormViewer::actionTriggered(int action)
{

}


void FormViewer::UpdateViewer()
{
    int nIndex = 0;
    int nRow = 1;
    int nColumn = 1;
    int nMode = m_nMode;
    int i=0;
    int j=0;

    nIndex = 0;

    nRow = 1;
    nColumn = 1;

    if(nMode==0)
    {
        nRow = 1;
        nColumn = 1;
    }
    else if(nMode==1)
    {
        nRow = 2;
        nColumn = 2;
    }
    else if(nMode==2)
    {
        nRow = 3;
        nColumn = 3;
    }



    nIndex = 0;

    CommonData* pCommonData = MainWindow::GetCommonData();
    HISTORY_STUDY* pHistoryStudy = pCommonData->GetCurrentHistoryStudy();
    //vector<ImageSelect*>* pListHistoryImage = pCommonData->GetListHistoryImage();


    for(i=0 ; i<nRow ; i++)
    {
        for(j=0 ; j<nColumn ; j++)
        {
            FormImageSelect* pForm = m_ListFormImageSelect[nIndex];

            int nDisplayIndex = m_nIndexCurrent+nIndex;
            //if(nDisplayIndex<pListHistoryImage->size())
            if(nDisplayIndex<m_ListImageSelect.size())
            {
                ImageSelect* pImageSelect = NULL;
                //if(pListHistoryImage->size() > nDisplayIndex)
                if(m_ListImageSelect.size() > nDisplayIndex)
                {
                    int k=0;
                    int nCheck = 0;
                    //for(k=0 ; k<pListHistoryImage->size() ; k++)
                    for(k=0 ; k<m_ListImageSelect.size() ; k++)
                    {
                        //ImageSelect* pImage = (*pListHistoryImage)[k];
                        ImageSelect* pImage = m_ListImageSelect[k];
                        if(pImage->m_bDelete==false)
                        {
                            if(nCheck==nDisplayIndex)
                            {
                                pImageSelect = pImage;
                                break;
                            }
                            nCheck++;
                        }
                    }
                    //pImageSelect = (*pListHistoryImage)[nDisplayIndex];
                }

                pForm->SetImageSelect(pImageSelect);
                if(pImageSelect!=NULL)
                {
                    //qDebug() << pImageSelect->m_strFile;
                }
            }
            else
            {
                pForm->SetImageSelect(NULL);
            }

            pForm->update();
            nIndex++;
        }
    }

    //update();

    QString strBirthDate = *pHistoryStudy->pStrPatientBirthDate;
    strBirthDate.insert(6, '/');
    strBirthDate.insert(4, '/');

    QString strStudyDate = *pHistoryStudy->pStrStudyDate;
    strStudyDate.insert(6, '/');
    strStudyDate.insert(4, '/');

    ui->info_ID->setText(*pHistoryStudy->pStrPatientID);
    ui->info_Name->setText(*pHistoryStudy->pStrPatientName);
    ui->info_StudyDate->setText(strStudyDate);
    ui->info_Birth->setText(strBirthDate);

    pCommonData->ReleaseCurrentHistoryStudy();

    //ui->gridLayoutWidget->update();
    //ui->gridLayout_Viewer->update();
}

void FormViewer::wheelEvent(QWheelEvent *event)
{
    int nDelta = event->delta();
    if(nDelta<0)
    {
        SingleDown();
    }
    else if(nDelta>0)
    {
        SingleUp();
    }
}

void FormViewer::on_pushButton_EXIT_clicked()
{
    CommonData* pCommonData = MainWindow::GetCommonData();
    SThreadImageSave* pThread = pCommonData->GetThreadCaptureImage();
    int nCurrentState = pThread->GetCurrentState();

    if(nCurrentState&0x08)
    {
        //Loading State
        pThread->CancelLoad();

        while(pThread->GetCurrentState()&0x08)
        {
            usleep(10*1000);
        }
    }

    int i=0;
    for(i=0 ; i<m_ListFormImageSelect.size() ; i++)
    {
        FormImageSelect* pForm = m_ListFormImageSelect[i];
        pForm->SetImageSelect(NULL);
    }

    pCommonData->ClearHistoryImage();

    m_ListImageSelect.clear();

    //UpdateViewer();




    ExitViewer();

    //pCommonData->ClearHistoryImage();
}

void FormViewer::Init()
{
    m_ListImageSelect.clear();
    m_nIndexCurrent = 0;
    m_nTotalImageCount = 0;

    m_bExecMenu = false;

    ui->verticalScrollBar->setValue(0);

    ui->pushButton_AddCapture->hide();
    ui->pushButton_DELETE->hide();
    ui->pushButton_SEND->hide();

    int i=0;
    for(i=0 ; i<m_ListFormImageSelect.size() ; i++)
    {
        FormImageSelect* pForm = m_ListFormImageSelect[i];
        pForm->SetImageSelect(NULL);
        pForm->Init();
    }

    ui->comboBox_ViewerMode->setCurrentIndex(0);
    ChangeViewMode(0);

    UpdateViewer();
}

void FormViewer::on_pushButton_SEND_clicked()
{
    //DialogProgress dlg(this);
    //dlg.exec();

    int i=0;

    CommonData* pCommonData = MainWindow::GetCommonData();
    vector<ImageSelect*>* pListHistoryImage = pCommonData->GetListHistoryImage();
    QList<QStringList> listFile;

    if(pCommonData->IsUseNetworkBackupVideo()==true && pListHistoryImage->size()>0)
    {
        vector<QString>* pListExport = pCommonData->GetExportList();
        pListExport->clear();

        ImageSelect* pHistoryImage = (*pListHistoryImage)[0];

        QString strFile = pHistoryImage->m_strFile;
        QFileInfo fi(strFile);
        QString strPath = fi.path();

        strPath = strPath.replace("/data/image/", "/data/video/");

        QStringList filter;
        if(strPath.size()>0)
        {
            QString strFilter = QString("*") + QString(MOVIE_FILE_EXTENSION);
            filter << strFilter;
        }

        QDirIterator it(strPath, filter, QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot, QDirIterator::NoIteratorFlags);
        QStringList listMovieFile;
        while(it.hasNext()==true)
        {
            QString strVideoFilename = it.next();
            listMovieFile << strVideoFilename;
            pListExport->push_back(strVideoFilename);
        }

        if(pListExport->size()>0)
        {
            BackupNetworkShareFolder("");

            pListExport->clear();
        }
    }




    for(i=0 ; i<pListHistoryImage->size() ; i++)
    {
        ImageSelect* pImageSelect = (*pListHistoryImage)[i];
        if(pImageSelect->m_bSelect==true && pImageSelect->m_nType==DISPLAY_IMAGE)
        {
            //`FileLocation`, `AcquisitionNumber`, `AcquisitionDate`, `AcquisitionTime`, `ImageDelete`, `ImageSend`

            QString strFile = pImageSelect->m_strFile;
            QString strAcquisitionNumber;
            QString strAcquisitionDate;
            QString strAcquisitionTime;
            QString strImageDelete;
            QString strImageSend;

            strAcquisitionNumber = QString("%1").arg(pImageSelect->m_nImageNumber);
            strAcquisitionDate = pImageSelect->m_strDate;
            strAcquisitionTime = pImageSelect->m_strTime;
            if(pImageSelect->m_bDelete==true)
            {
                strImageDelete = "1";
            }
            else
            {
                strImageDelete = "0";
            }

            if(pImageSelect->m_bSend==true)
            {
                strImageSend = "1";
            }
            else
            {
                strImageSend = "0";
            }

            QStringList listData;
            listData.push_back(strFile);
            listData.push_back(strAcquisitionNumber);
            listData.push_back(strAcquisitionDate);
            listData.push_back(strAcquisitionTime);
            listData.push_back(strImageDelete);
            listData.push_back(strImageSend);

            listFile.push_back(listData);
        }

    }

    pCommonData->ReleaseListHistoryImage();


    if(listFile.size()>0)
    {
        SThreadSendDICOM* pThreadSendDICOM = pCommonData->GetThreadSendDICOM();
        pThreadSendDICOM->SetSendImageList(listFile);

        if(m_pDialogSendProgress!=NULL)
        {
            delete m_pDialogSendProgress;
        }

        m_pDialogSendProgress = new DialogProgress(this);

        //m_pDialogSendProgress->Init(1);
        m_pDialogSendProgress->Init(0x11);
        m_pDialogSendProgress->exec();

        // --- DB 업데이트 로직 수정 ---
        vector<QString> listImageSendCompleteFile = pThreadSendDICOM->GetListImageSendCompleteFile();
        if (!listImageSendCompleteFile.empty())
        {
            // 2. 이 작업을 위한 지역 DB 인스턴스를 생성합니다.
            SUTIL::SDatabase db(QString("SendUpdate_%1").arg(reinterpret_cast<quintptr>(this)));
            if (db.OpenDatabase("/home/birdhead/test.db") == 0)
            {
                // 3. WHERE IN 절을 사용하여 단 한 번의 쿼리로 모든 데이터를 업데이트합니다. (가장 효율적인 방법)
                QStringList placeholders;
                for (size_t i = 0; i < listImageSendCompleteFile.size(); ++i) {
                    placeholders << "?";
                }

                QString query = QString("UPDATE Image SET ImageSend = 1 WHERE FileLocation IN (%1)")
                        .arg(placeholders.join(','));

                QVariantList params;
                for (const QString& file : listImageSendCompleteFile) {
                    params << file;
                }

                db.ExecuteNonQuery(query, params);
            }
        }

    }

    //SDatabase::DeleteListReponse(listFile);
    listFile.clear();
}

void FormViewer::UpdateMakeDICOMInfo(int nCount, int nTotalCount)
{
    m_pDialogSendProgress->DisplayInfo(nCount, nTotalCount);

    QString strInfo = QString("DICOM Make %1 / %2").arg(nCount).arg(nTotalCount);
    m_pDialogSendProgress->DisplayInfo(strInfo);
}

void FormViewer::UpdateSendInfo(int nCount, int nTotalCount)
{
    m_pDialogSendProgress->DisplayInfo(nCount, nTotalCount);

    QString strInfo = QString("%1 / %2").arg(nCount).arg(nTotalCount);
    m_pDialogSendProgress->DisplayInfo(strInfo);
}

void FormViewer::UpdateSendComplete()
{
    m_pDialogSendProgress->DisplayInfo(-1, 100);

    QString strInfo = QString("Send Complete");
    m_pDialogSendProgress->DisplayInfo(strInfo);

    QThread::msleep(1000);

    //m_pDialogSendProgress->SendComplete();
    //m_pDialogSendProgress->accept();
}

void FormViewer::UpdateSendFailed()
{
    m_pDialogSendProgress->DisplayInfo(-1, 100);

    //QString strInfo = QString("Error: Check Network");
    //m_pDialogSendProgress->DisplayInfo(strInfo);
    m_pDialogSendProgress->DisplayInfo(-1);

    //QThread::msleep(1000);

    //m_pDialogSendProgress->SendComplete();
    //m_pDialogSendProgress->accept();
}

void FormViewer::SetTotalImageCount(int nCount)
{
    m_nTotalImageCount = nCount;

    if(m_nTotalImageCount==0)
    {
        ImageLoadComplete();
    }
}

void FormViewer::SetImageLoadInfo(int nLoad, int nTotal, ImageSelect* pImageSelectLoad)
{
    if(nLoad>=nTotal)
    {
        return;
    }

    m_ListImageSelect.push_back(pImageSelectLoad);

    int nIndex = 0;
    int nRow = 1;
    int nColumn = 1;
    int nMode = m_nMode;
    int i=0;
    int j=0;

    nIndex = 0;

    nRow = 1;
    nColumn = 1;

    if(nMode==0)
    {
        nRow = 1;
        nColumn = 1;
    }
    else if(nMode==1)
    {
        nRow = 2;
        nColumn = 2;
    }
    else if(nMode==2)
    {
        nRow = 3;
        nColumn = 3;
    }

    nIndex = 0;

    int nIndexMaxView = m_nIndexCurrent + (nRow * nColumn-1);

    if(nLoad<=nIndexMaxView && nLoad>=m_nIndexCurrent)
    {

    }
    else
    {
        return;
    }

    //CommonData* pCommonData = MainWindow::GetCommonData();
    //vector<ImageSelect*>* pListHistoryImage = pCommonData->GetListHistoryImage();



    m_nPageTotal = m_nTotalImageCount / (nRow*nColumn);
    if(m_nTotalImageCount%(nRow*nColumn)!=0)
    {
        m_nPageTotal++;
    }

    m_nPageCurrent = (int)(nLoad / (nRow*nColumn)) + 1;

    for(i=0 ; i<nRow ; i++)
    {
        for(j=0 ; j<nColumn ; j++)
        {
            FormImageSelect* pForm = m_ListFormImageSelect[nIndex];

            int nDisplayIndex = m_nIndexCurrent+nIndex;
            //if(nDisplayIndex<pListHistoryImage->size())
            if(nDisplayIndex<m_ListImageSelect.size())
            {
                ImageSelect* pImageSelect = NULL;
                //if(pListHistoryImage->size() > nDisplayIndex)
                if(m_ListImageSelect.size() > nDisplayIndex)
                {
                    int k=0;
                    int nCheck = 0;
                    for(k=0 ; k<m_ListImageSelect.size() ; k++)
                    {
                        ImageSelect* pImage = m_ListImageSelect[k];
                        if(pImage->m_bDelete==false)
                        {
                            if(nCheck==nDisplayIndex)
                            {
                                pImageSelect = pImage;
                                break;
                            }
                            nCheck++;
                        }
                    }
                    //pImageSelect = (*pListHistoryImage)[nDisplayIndex];
                }

                pForm->SetImageSelect(pImageSelect);
                if(pImageSelect!=NULL)
                {
                    //qDebug() << pImageSelect->m_strFile;
                }
            }
            else
            {
                pForm->SetImageSelect(NULL);
            }

            pForm->update();
            nIndex++;
        }
    }

    QString strIndexPage = QString("Page Index: %1/%2").arg(m_nPageCurrent).arg(m_nPageTotal);
    ui->info_DisplayIndex->setText(strIndexPage);

    QString strInfoStoage = QString("IMG: %1").arg(nTotal);
    ui->info_Storage->setText(strInfoStoage);
}

void FormViewer::on_pushButton_Rotate_clicked()
{
    int i = 0;
    for(i=0 ; i<9 ; i++)
    {
        FormImageSelect* pForm = m_ListFormImageSelect[i];
        bool bSelect = pForm->IsSelect();

        if(bSelect==true)
        {
            pForm->DisplayRotate();
        }
    }
}


void FormViewer::on_pushButton_ZoomInOut_clicked()
{
    int i = 0;
    for(i=0 ; i<9 ; i++)
    {
        FormImageSelect* pForm = m_ListFormImageSelect[i];
        bool bSelect = pForm->IsSelect();

        if(bSelect==true)
        {
            pForm->setCursor(Qt::ClosedHandCursor);
            pForm->EnableZoom(true);
        }
        else
        {
            pForm->EnableZoom(false);
        }
    }
}

void FormViewer::on_pushButton_FlipHorizontal_clicked()
{
    int i = 0;
    for(i=0 ; i<9 ; i++)
    {
        FormImageSelect* pForm = m_ListFormImageSelect[i];
        bool bSelect = pForm->IsSelect();

        if(bSelect==true)
        {
            pForm->DisplayFlipHorizontal();
        }
    }
}

void FormViewer::on_pushButton_FlipVertical_clicked()
{
    int i = 0;
    for(i=0 ; i<9 ; i++)
    {
        FormImageSelect* pForm = m_ListFormImageSelect[i];
        bool bSelect = pForm->IsSelect();

        if(bSelect==true)
        {
            pForm->DisplayFlipVertical();
        }
    }
}

void FormViewer::on_pushButton_Move_clicked()
{
    int i = 0;
    for(i=0 ; i<9 ; i++)
    {
        FormImageSelect* pForm = m_ListFormImageSelect[i];
        bool bSelect = pForm->IsSelect();

        if(bSelect==true)
        {
            pForm->setCursor(Qt::ClosedHandCursor);
            pForm->EnableMove(true);
        }
        else
        {
            pForm->EnableMove(false);
        }
    }
}


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

    int nFontSize = 22;
    int nFontSizeCaptureTitle = 30;
    int nFontSizeButton = 22;
    int nFontInfoLabel = 22;
    int nFontInfoInfo = 22;
    int nScrollWidth = 26;
    if(nDisplayType==SDISPLAY_1280X1024)
    {
        nFontSize = 16;
        nFontSizeCaptureTitle = 25;
        nFontSizeButton = 18;
        nFontInfoLabel = 18;
        nFontInfoInfo = 22;
        //ui->frame_Viewer_Vertical->hide();
        //ui->frame_Viewer_Horizontal->show();
        ui->frame_capture->setGeometry(40, 45, 1200, 1024-90);
        ui->label_Viewer->setGeometry(38, 24, 300, 45);
        ui->pushButton_EXIT->setGeometry(1003, 22, 140, 45);
        ui->frame_Line->setGeometry(38, 69, 965+140, 27);
        ui->display_line->setGeometry(0, 27/2, 965+140, 1);
        //ui->frame_InfoString->setGeometry(38, 69+27, 965+140, 59);
        ui->frame_InfoString->setGeometry(152, 24, 760, 45);
        {
            ui->label_ID->setGeometry(0, 0, 30, 45);
            ui->info_ID->setGeometry(40, 0, 160, 45);
            ui->label_Name->setGeometry(180, 0, 70, 45);
            ui->info_Name->setGeometry(260, 0, 160, 45);
            ui->label_StudyDate->setGeometry(450, 0, 120, 45);
            ui->info_StudyDate->setGeometry(600, 0, 160, 45);
            ui->label_Birth->hide();
            ui->info_Birth->hide();
        }
        ui->gridLayoutWidget->setGeometry(39, 155, 1103, 621);
        ui->pushButton_SEND->setGeometry(1029, 155+621+61-45, 115, 45);
        ui->pushButton_DELETE->setGeometry(1029, 155+621+133-45, 115, 45);

        ui->pushButton_AddCapture->setGeometry(39, 155+621+61-45, 125, 45);

        ui->info_DisplayIndex->setGeometry(880, 96, 260, 48);

        {
            nScrollWidth = 20;
            ui->frame_verticalScrollBar->setGeometry(1144, 155, 20, 622);
            ui->verticalScrollBar->setGeometry(0, 0, 20, 622);
            //ui->horizontalSlider_Hue->setGeometry(310, 40, 300, 16);
            //ui->horizontalSlider_Saturation->setGeometry(650, 40, 300, 16);
        }

        ui->comboBox_ViewerMode->setGeometry(80-40, 140-45, 120, 30);

        //ui->frame_Viewer_Horizontal->setGeometry(95, 155+621+61-45, 1029-150, 117);
    }
    else if(nDisplayType==SDISPLAY_1920X1080)
    {
        nFontSizeCaptureTitle = 30;
        nFontSizeButton = 22;
        nFontInfoLabel = 22;
        nFontInfoInfo = 22;
        //ui->frame_Viewer_Vertical->show();
        //ui->frame_Viewer_Horizontal->hide();
        ui->frame_capture->setGeometry(36, 36, 1855, 1028);
        ui->label_Viewer->setGeometry(55, 30, 200, 40);
        ui->pushButton_EXIT->setGeometry(1580, 27, 161, 51);
        ui->frame_Line->setGeometry(55, 80, 1749, 53);
        ui->display_line->setGeometry(0, 53/2, 1749, 1);
        //ui->frame_Info->setGeometry(0, 133, 1855, 96);
        //ui->pushButton_ACQ->setGeometry(1399, 0, 153, 63);
        //ui->pushButton_VID->setGeometry(1591, 0, 153, 63);
        ui->frame_InfoString->setGeometry(55, 0, 800, 63);
        {
            ui->label_ID->setGeometry(0, 0, 30, 63);
            ui->info_ID->setGeometry(40, 0, 161, 63);
            ui->label_Name->setGeometry(200, 0, 70, 63);
            ui->info_Name->setGeometry(280, 0, 161, 63);
            ui->label_Birth->setGeometry(490, 0, 70, 63);
            ui->info_Birth->setGeometry(570, 0, 161, 63);
        }
        //ui->widget_Video->setGeometry(55, 230, 1280, 720);
        ui->pushButton_SEND->setGeometry(1398, 940, 161, 51);
        ui->pushButton_DELETE->setGeometry(1582, 940, 161, 51);

        {
            //ui->horizontalSlider_Hue->setGeometry(310, 40, 451, 16);
            //ui->horizontalSlider_Saturation->setGeometry(840, 40, 451, 16);
        }
    }

    QString strCaptureTitle = QString(
    "QLabel \
    { \
        font-family: 'Roboto'; \
        font-size: %1px; \
        font-weight: bold; \
        color: #000000;	\
    }").arg(nFontSizeCaptureTitle);
    ui->label_Viewer->setStyleSheet(strCaptureTitle);

    QString strPushButton_Exit_Delete = QString(
    "QPushButton \
    { \
        background: #FFFFFF; \
        font-family: 'Roboto'; \
        font-size: %1px; \
        font-weight: bold; \
        border-radius: 8px; \
        color: black; \
    } \
    QPushButton:pressed \
    { \
        background: #D8D8D8; \
    }").arg(nFontSizeButton);
    ui->pushButton_EXIT->setStyleSheet(strPushButton_Exit_Delete);
    ui->pushButton_DELETE->setStyleSheet(strPushButton_Exit_Delete);

    QString strPushButton_ACQ_VID = QString(
    "QPushButton \
    { \
        background: #153B44; \
        font-family: 'Roboto'; \
        font-size: %1px; \
        font-weight: bold; \
        border-radius: 8px; \
        color: white; \
    } \
    QPushButton:pressed \
    { \
        background: #1B4C54; \
    }").arg(nFontSizeButton);
    //ui->pushButton_ACQ->setStyleSheet(strPushButton_ACQ_VID);
    //ui->pushButton_VID->setStyleSheet(strPushButton_ACQ_VID);
    ui->pushButton_SEND->setStyleSheet(strPushButton_ACQ_VID);



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

    ui->pushButton_AddCapture->setStyleSheet(strPushButton_AddCapture);


    QString strInfoLabel = QString(
    "QLabel \
    { \
        font-family: 'Roboto'; \
        font-size: %1px; \
        font-weight: bold; \
        color: #000000; \
    }").arg(nFontInfoLabel);
    ui->label_ID->setStyleSheet(strInfoLabel);
    ui->label_Name->setStyleSheet(strInfoLabel);
    ui->label_Birth->setStyleSheet(strInfoLabel);
    ui->label_StudyDate->setStyleSheet(strInfoLabel);

    QString strInfoInfo = QString(
    "QLabel \
    { \
        font-family: 'Roboto'; \
        font-size: %1px; \
        font-weight: normal; \
        color: #000000; \
    }").arg(nFontInfoInfo);
    ui->info_ID->setStyleSheet(strInfoInfo);
    ui->info_Name->setStyleSheet(strInfoInfo);
    ui->info_Birth->setStyleSheet(strInfoInfo);
    ui->info_StudyDate->setStyleSheet(strInfoInfo);

    QString strVerticalScroll = QString(
    "QScrollBar\n"
    "{ \n"
        "background: none; \n"
        "border: none; \n"
        "border-image: url(://image/scrollbar_vertical_bg.png); \n"
    "}     \n"
    "QScrollBar:vertical { \n"
    "    background: white; \n"
    "    width: %1px; \n"
    "    margin: %1px 0px %1px 0px; \n"
    "} \n"
    "QScrollBar::handle:vertical { \n"
    "    background: none; \n"
    "    margin: 4px; \n"
    "    width: 18px; \n"
    "    min-height: 20px; \n"
    "    max-height: 20px; \n"
    "    height: 36px; \n"
    "    border-image: url(://image/ScrollBar_Vertical_Icon.png); \n"
    "} \n"
    "QScrollBar::add-line:vertical { \n"
    "    border: solid 1px black; \n"
    "    background: none; \n"
    "    border-image: url(://image/scrollbar_down.png); \n"
    "    height: %1px; \n"
    "    margin: 0px 0px; \n"
    "    subcontrol-position: bottom; \n"
    "    subcontrol-origin: margin; \n"
    "    border-bottom-left-radius: %2px; \n"
    "    border-bottom-right-radius: %2px; \n"
    "} \n"
    "QScrollBar::sub-line:vertical { \n"
    "    border: none; \n"
    "    background: none; \n"
    "    border-image: url(://image/scrollbar_up.png); \n"
    "    height: %1px; \n"
    "    subcontrol-position: top; \n"
    "    subcontrol-origin: margin; \n"
    "}").arg(nScrollWidth).arg(nScrollWidth/2);

    ui->verticalScrollBar->setStyleSheet(strVerticalScroll);

    QString strVerticalFrame = QString(
    "QFrame \n"
    "{ \n"
    "    border: 1px solid black; \n"
    "    border-radius: %1px; \n"
    "}").arg(nScrollWidth/2-2);
    ui->frame_verticalScrollBar->setStyleSheet(strVerticalFrame);
}

void FormViewer::on_pushButton_DELETE_clicked()
{
    CommonData* pCommonData = MainWindow::GetCommonData();
    vector<ImageSelect*>* pListHistoryImage = pCommonData->GetListHistoryImage();


    //vector<ImageSelect*> listHistory;

    m_ListImageSelect.clear();

    int i=0;
    int nTotalImageCount = 0;
    for(i=0 ; i<pListHistoryImage->size() ; i++)
    {
        ImageSelect* pImageSelect = (*pListHistoryImage)[i];
        if(pImageSelect->m_bSelect==true)
        {
            QString strFile = pImageSelect->m_strFile;
            QString strImageInstanceUID = pImageSelect->m_strImageInstanceUID;

            if(pImageSelect->m_nType==DISPLAY_VIDEO)
            {
                QFileInfo fileCheck(strFile);
                if(fileCheck.exists()==true)
                {
                    QString strPath = fileCheck.path();
                    QString strFilename = fileCheck.fileName();

                    QStringList filter;
                    if(strFilename.size()>0)
                    {
                        strFilename = strFilename.left(strFilename.size()-4);
                        filter << strFilename + QString("*") + MOVIE_FILE_EXTENSION;
                    }

                    QDirIterator it(strPath, filter, QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot, QDirIterator::NoIteratorFlags);
                    while(it.hasNext()==true)
                    {
                        QString strVideoFilename = it.next();
                        QFile fileDelete(strVideoFilename);
                        if(fileDelete.exists()==true)
                        {
                            fileDelete.remove();
                            fileDelete.close();
                        }
                    }
                }

                QFile fileDelete(strFile);
                if(fileDelete.exists()==true)
                {
                    fileDelete.remove();
                    fileDelete.close();
                }

                strFile.replace(".bmp", MOVIE_FILE_EXTENSION);
                strFile.replace(".jpg", MOVIE_FILE_EXTENSION);
                strFile.replace(".png", MOVIE_FILE_EXTENSION);
            }


            {
                SUTIL::SDatabase db(QString("ImageDeleteTask_%1").arg(reinterpret_cast<quintptr>(this)));
                if (db.OpenDatabase("/home/birdhead/test.db") == 0) // 0이 성공
                {
                    // 2. 지역 인스턴스 'db'를 사용하여 안전하게 함수를 호출합니다.
                    //    리팩토링된 함수는 bool 값을 반환하므로, 성공 여부를 확인할 수 있습니다.
                    bool bSuccess = db.ImageDeleteFromImageInstanceUID(strImageInstanceUID, true);

                    if (bSuccess) {
                        qDebug() << "Successfully marked image for deletion:" << strImageInstanceUID;
                    } else {
                        qWarning() << "Failed to mark image for deletion:" << strImageInstanceUID;
                    }
                }
                else
                {
                    qWarning() << "DB open failed for ImageDeleteTask.";
                }
            }

            pImageSelect->DeleteImageData();
            //pImageSelect->m_bDelete = true;
            //delete pImageSelect->m_pImage;

        }
        else
        {
            nTotalImageCount++;

            //listHistory.push_back(pImageSelect);
            m_ListImageSelect.push_back(pImageSelect);
        }
    }

    pListHistoryImage->clear();
    for(i=0 ; i<m_ListImageSelect.size() ; i++)
    {
        ImageSelect* pImageSelect = m_ListImageSelect[i];

        pListHistoryImage->push_back(pImageSelect);
    }

    pCommonData->ReleaseListHistoryImage();


    if(nTotalImageCount!=m_nTotalImageCount)
    {
        SetTotalImageCount(nTotalImageCount);

        m_nIndexCurrent = 0;
        //ChangeViewMode(m_nMode);


        ui->verticalScrollBar->setValue(0);

        UpdateViewer();
    }
}

void FormViewer::on_pushButton_AddCapture_clicked()
{
    CommonData* pCommonData = MainWindow::GetCommonData();

    SThreadImageSave* pThread = pCommonData->GetThreadCaptureImage();
    int nCurrentState = pThread->GetCurrentState();

    if(nCurrentState&0x08)
    {
        //Loading State
        pThread->CancelLoad();

        while(pThread->GetCurrentState()&0x08)
        {
            usleep(10*1000);
        }

    }

    if(m_bExecMenu==false)
    {
        ACQUISITION_INFO* pAcquisitionInfo = pCommonData->GetAcquisitionInfo();
        //vector<ImageSelect*>* pListHistoryImage = pCommonData->GetListHistoryImage();
        HISTORY_STUDY* pHistoryStudy = pCommonData->GetCurrentHistoryStudy();

        pAcquisitionInfo->GetPatientInfo()->strPatientAge = pHistoryStudy->pStrPatientAge->toStdString().c_str();
        pAcquisitionInfo->GetPatientInfo()->strPatientID = pHistoryStudy->pStrPatientID->toStdString().c_str();
        pAcquisitionInfo->GetPatientInfo()->strPatientName = pHistoryStudy->pStrPatientName->toStdString().c_str();
        pAcquisitionInfo->GetPatientInfo()->strPatientSex = pHistoryStudy->pStrPatientSex->toStdString().c_str();
        pAcquisitionInfo->GetPatientInfo()->strPatientBirthDate = pHistoryStudy->pStrPatientBirthDate->toStdString().c_str();
        pAcquisitionInfo->GetPatientInfo()->strPatientLocation = pHistoryStudy->pStrPatientLocation->toStdString().c_str();

        pAcquisitionInfo->GetStudyInfo()->nPatientIndex = pHistoryStudy->pStrPatientIndex->toInt();
        pAcquisitionInfo->GetStudyInfo()->strStudyInstanceUID = pHistoryStudy->pStrStudyInstanceUID->toStdString().c_str();
        pAcquisitionInfo->GetStudyInfo()->strStudyDate = pHistoryStudy->pStrStudyDate->toStdString().c_str();
        pAcquisitionInfo->GetStudyInfo()->strStudyTime = pHistoryStudy->pStrStudyTime->toStdString().c_str();
        pAcquisitionInfo->GetStudyInfo()->strAccessionNumber = pHistoryStudy->pStrAccessionNumber->toStdString().c_str();
        pAcquisitionInfo->GetStudyInfo()->strStudyDescription = pHistoryStudy->pStrStudyDescription->toStdString().c_str();
        pAcquisitionInfo->GetStudyInfo()->strReferringPhysiciansName = pHistoryStudy->pStrReferringPhysiciansName->toStdString().c_str();

        pAcquisitionInfo->GetSeriesInfo()->strSeriesInstanceUID = pHistoryStudy->pStrSeriesInstanceUID->toStdString().c_str();
        pAcquisitionInfo->GetSeriesInfo()->strModality = pHistoryStudy->pStrModality->toStdString().c_str();
        pAcquisitionInfo->GetSeriesInfo()->strSeriesDate = pHistoryStudy->pStrSeriesDate->toStdString().c_str();
        pAcquisitionInfo->GetSeriesInfo()->strSeriesTime = pHistoryStudy->pStrSeriesTime->toStdString().c_str();
        pAcquisitionInfo->GetSeriesInfo()->strSeriesDescription = pHistoryStudy->pStrSeriesDescription->toStdString().c_str();
        pAcquisitionInfo->GetSeriesInfo()->strOperatorsName = pHistoryStudy->pStrOperatorsName->toStdString().c_str();
        pAcquisitionInfo->GetSeriesInfo()->nSeriesNumber = pHistoryStudy->pStrSeriesNumber->toInt();

        pAcquisitionInfo->m_nIndexStudy = pHistoryStudy->pStrStudyIndex->toInt();

        {
            SUTIL::SDatabase db(QString("GetSeriesIndices_Task_%1").arg(reinterpret_cast<quintptr>(this)));
            if (db.OpenDatabase("/home/birdhead/test.db") == 0) // 0이 성공
            {
                // 2. 지역 인스턴스 'db'를 사용하여 안전하게 함수를 호출합니다.
                //    Get...Index... 함수들은 이전에 리팩토링되어 이미 안전합니다.
                //    pStrStudyInstanceUID가 QString* 이므로 역참조(*)하여 const QString& 타입으로 전달합니다.
                pAcquisitionInfo->m_nIndexSeries_Image = db.GetSeriesImageIndexWithInstanceUID(*pHistoryStudy->pStrStudyInstanceUID);
                pAcquisitionInfo->m_nIndexSeries_Video = db.GetSeriesVideoIndexWithInstanceUID(*pHistoryStudy->pStrStudyInstanceUID);
            }
            else
            {
                qWarning() << "DB open failed for GetSeriesIndices task.";
                // 기본값으로 초기화
                pAcquisitionInfo->m_nIndexSeries_Image = 0;
                pAcquisitionInfo->m_nIndexSeries_Video = 0;
            }
        }

        pAcquisitionInfo->m_nIndexPatient = pHistoryStudy->pStrPatientIndex->toInt();

        pAcquisitionInfo->m_nAcquisitionImageMax = pHistoryStudy->pStrImageCount->toInt();
        pAcquisitionInfo->m_nAcquisitionVideoMax = pHistoryStudy->pStrMovieCount->toInt();

        //pAcquisitionInfo->m_nAcuqisitionMax = pDatabase->GetImageMaxIndex(pHistoryStudy->pStrSeriesInstanceUID);

        pCommonData->ReleaseCurrentHistoryStudy();

        pCommonData->ReleaseAcquisitionInfo();

        m_bExecMenu = true;
        //ExecuteCapture();

        pCommonData->AddCaptureImageWithHistory();

        ChangeMenu(SMENU_CAPTURE);
    }
}



void FormViewer::ImageLoadComplete()
{
    ui->pushButton_AddCapture->show();
    ui->pushButton_DELETE->show();
    ui->pushButton_SEND->show();
}
