#include "formlistwidgethistory.h"
#include "mainwindow.h"

#include "mainwindow.h"
#include <QFileInfo>
#include <QDirIterator>

FormListWidgetHistory::FormListWidgetHistory(QWidget *parent) : FormListWidget(parent)
{
    connect(m_pListWidget, SIGNAL(ListSingleDown()), this, SLOT(ListSingleDown()));
    connect(m_pListWidget, SIGNAL(ListSingleUp()), this, SLOT(ListSingleUp()));

    m_nMaxItemShow = 10;

    m_pListWidget->SetListType(SWIDGET_HISTORY);
}

FormListWidgetHistory::~FormListWidgetHistory()
{
    disconnect(m_pListWidget, SIGNAL(ListSingleDown()), this, SLOT(ListSingleDown()));
    disconnect(m_pListWidget, SIGNAL(ListSingleUp()), this, SLOT(ListSingleUp()));

    Clear();
}

void FormListWidgetHistory::ExecuteMenu()
{
    ChangeMenu(SMENU_VIEWER);
}

void FormListWidgetHistory::ChangeHeader()
{
    FormListWidget::ChangeHeader();

    m_pListWidget->SetResizeEnableHeader(false);
    m_pListWidget->ChangeHeader();
    m_pListWidget->SetResizeEnableHeader(true);
}

void FormListWidgetHistory::Clear()
{
    m_pListWidget->Clear();
}

void FormListWidgetHistory::UpdateHistoryList()
{
    m_pListWidget->UpdateHistoryList();

    CommonData* pCommonData = MainWindow::GetCommonData();
    vector<HISTORY_STUDY*>* pListHistoryStudy = pCommonData->GetHistorySearchResult();

    if(pListHistoryStudy->size()>m_nMaxItemShow)
    {
        m_pVerticalScrollBar->setValue(0);
        m_pVerticalScrollBarWidget->show();
    }
    else
    {
        m_pVerticalScrollBarWidget->hide();
    }

    m_pListWidget->CheckHorizontalScroll();

}

void FormListWidgetHistory::CellDoubleClicked(int nRow, int nColumn)
{
    CommonData* pCommonData = MainWindow::GetCommonData();
    vector<HISTORY_STUDY*>* pListHistoryStudy = pCommonData->GetHistorySearchResult();

    if(nRow < pListHistoryStudy->size())
    {
        if(m_bExecute==false)
        {
            vector<TableHeader*>* pListActivate = pCommonData->GetHistoryTableHeader()->GetListActive();
            vector<TableHeader*>::iterator it;
            int nSelectIndex = -1;

            int nIndex = 0;
            QTableWidgetItem * pItem = NULL;
            QString strSelectIndex;

            for(it=pListActivate->begin() ; it!=pListActivate->end() ; ++it)
            {
                TableHeader* pTableHeader = (*it);
                int nOriIndex = pTableHeader->m_nIndex;
                int nDefaultIndex = pTableHeader->m_nIndexDefault;
                if(nDefaultIndex==SDI_INDEX)
                {
                    nIndex = nDefaultIndex;
                    pItem = m_pListWidget->item(nRow, nOriIndex);
                    strSelectIndex = pItem->text();
                    break;
                }
            }

            int i=0;

            if(strSelectIndex.size()>0)
            {
                for(i=0 ; i<pListHistoryStudy->size() ; i++)
                {
                    HISTORY_STUDY* pHistoryStudy = (*pListHistoryStudy)[i];
                    QString strIndex = pHistoryStudy->GetData(nIndex);
                    if(strSelectIndex==strIndex)
                    {
                        nSelectIndex = i;
                        break;
                    }
                }
            }

            if(nSelectIndex<0)
            {
                nSelectIndex = nRow;
            }


            m_nCurrentRowIndex = nSelectIndex;
            CommonData* pCommonData = MainWindow::GetCommonData();
            pCommonData->ClearHistoryImage();

            pCommonData->SetCurrentHistoryStudy(m_nCurrentRowIndex);



            ExecuteMenu();
            m_bExecute = true;
        }

    }
}

void FormListWidgetHistory::ListSingleDown()
{
    CommonData* pCommonData = MainWindow::GetCommonData();
    QScrollBar* pScrollBar = m_pListWidget->verticalScrollBar();
    float fMaxValue = 199.0f;
    float fMaxScrollBar = 0.0f;

    vector<HISTORY_STUDY*>* pListHistoryStudy = pCommonData->GetHistorySearchResult();
    int nHistoryCount = pListHistoryStudy->size();
    int nRemain = nHistoryCount - m_nMaxItemShow;

    float fRatio = (float)fMaxValue / (float)nRemain + 1.5f;

    int nValue = m_pVerticalScrollBar->value();
    nValue = nValue + fRatio;
    if(nValue > fMaxValue)
    {
        nValue = (int)fMaxValue;
    }

    m_pVerticalScrollBar->setValue(nValue);
}

void FormListWidgetHistory::ListSingleUp()
{
    CommonData* pCommonData = MainWindow::GetCommonData();
    QScrollBar* pScrollBar = m_pListWidget->verticalScrollBar();
    float fMaxValue = 199.0f;
    float fMaxScrollBar = 0.0f;

    vector<HISTORY_STUDY*>* pListHistoryStudy = pCommonData->GetHistorySearchResult();
    int nHistoryCount = pListHistoryStudy->size();
    int nRemain = nHistoryCount - m_nMaxItemShow;

    float fRatio = (float)fMaxValue / (float)nRemain + 1.5f;

    int nValue = m_pVerticalScrollBar->value();
    nValue = nValue - fRatio;
    if(nValue < 0)
    {
        nValue = 0;
    }

    m_pVerticalScrollBar->setValue(nValue);
}


void FormListWidgetHistory::Init()
{
    m_bExecute = false;
    FormListWidget::Init();

    m_pListWidget->InitHeader();
    m_pListWidget->setCurrentCell(-1, -1);
    m_pListWidget->CheckHorizontalScroll();

    setFocus(Qt::OtherFocusReason);
    m_pListWidget->setFocus(Qt::OtherFocusReason);
}


void FormListWidgetHistory::GetExportList()
{
    CommonData* pCommonData = MainWindow::GetCommonData();
    vector<HISTORY_STUDY*>* pListHistorySearch = pCommonData->GetHistorySearchResult();
    vector<QString>* pListExport = pCommonData->GetExportList();

    QModelIndexList selection = m_pListWidget->selectionModel()->selectedRows();

    pListExport->clear();

    if (selection.isEmpty()) {
        return; // 선택된 항목이 없으면 바로 종료
    }

    // 1. 루프 시작 전에 단 하나의 지역 DB 인스턴스를 생성합니다.
    SUTIL::SDatabase db(QString("GetExportList_%1").arg(reinterpret_cast<quintptr>(this)));
    if (db.OpenDatabase("/home/birdhead/test.db") != 0) {
        qWarning() << "DB open failed for GetExportList.";
        return;
    }

    // 2. 선택된 항목들을 순회합니다.
    for (const QModelIndex& index : selection)
    {
        int nIndex = index.row();
        if (nIndex < pListHistorySearch->size())
        {
            HISTORY_STUDY* pHistory = (*pListHistorySearch)[nIndex];
            if (!pHistory || !pHistory->pStrStudyIndex) continue;

            int studyIndex = pHistory->pStrStudyIndex->toInt();

            // 3. 새로 만든 효율적인 함수를 "한 번만" 호출하여 모든 파일 목록을 가져옵니다.
            vector<QString> allFiles = db.GetAllFilesForStudyIndex(studyIndex);

            // 4. 조회된 결과를 최종 목록에 추가합니다.
            pListExport->insert(pListExport->end(), allFiles.begin(), allFiles.end());
        }
    }
    // 함수가 끝나면 'db' 객체는 자동으로 소멸되어 모든 자원이 정리됩니다.
}


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

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

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