#include "headertype1.h"

#include <QEvent>

#include <QPainter>

#include <QDebug>
#include "mainwindow.h"

#include "common.h"

#include "slistwidget.h"


HeaderType1::HeaderType1(Qt::Orientation orientation, QWidget *parent) : QHeaderView(orientation, parent)
{
    m_bResizeEnable = false;
    m_nListType = 0;
    m_nHorizontalOffset = 0;
    int i=0;
    for(i=0 ; i<2 ; i++)
    {
        FormHeaderType1* pHeaderType1 = new FormHeaderType1(this);
        pHeaderType1->SetID(i);

        connect(pHeaderType1, SIGNAL(Clicked(int)), this, SLOT(Clicked(int)));

        pHeaderType1->hide();
        pHeaderType1->Unselect();
        m_ListHeader.push_back(pHeaderType1);
    }

    connect(this, SIGNAL(sectionResized(int, int, int)), this, SLOT(sectionResized(int, int, int)));

    m_pHeaderCurrent = m_ListHeader[0];
    //m_pHeaderCurrent->Select(Qt::AscendingOrder);

    setStyleSheet(
                        //"QTableWidget {background-color: transparent; border: none; outline: none; color:black;}"
                        //"QHeaderView { border:none; border-bottom: 3px solid rgb(0, 160, 230); background: rgb(57, 58, 60); min-height: 60px;}"
                        "QHeaderView { border:none; border-bottom: 0px solid #153b44; background: transparent; min-height: 60px;}"

                        "QHeaderView::section:horizontal { border:none; border-right: 1px solid white; color: white; background: transparent ; padding-left: 10px; }"
                        "QHeaderView::section:horizontal:hover { background: rgb(0, 160, 230);}"
                        "QHeaderView::section:horizontal:pressed { background: rgb(0, 180, 255);}"
                        "QHeaderView::up-arrow { width: 23px; height: 12px; padding-right: 25px; image: url(://image/Arrow_top_2.png); subcontrol-position: center right; }"
                        "QHeaderView::down-arrow { width: 23px; height: 12px; padding-right: 25px; image: url(://image/Arrow_under_2.png); subcontrol-position: center right; }");

    setSortIndicatorShown(true);

    //setStretchLastSection(true);
}

HeaderType1::~HeaderType1()
{

}

void HeaderType1::ChangeStyle()
{

}

void HeaderType1::Clicked(int nID)
{
    SListWidget* pParentWidget = (SListWidget*)this->parentWidget();
    if(pParentWidget!=NULL)
    {
        pParentWidget->setSortingEnabled(true);
    }
    if(nID==m_pHeaderCurrent->GetID())
    {
        int nOrder = m_pHeaderCurrent->GetOrder();

        if(nOrder==Qt::AscendingOrder)
        {
            nOrder = Qt::DescendingOrder;
        }
        else
        {
            nOrder = Qt::AscendingOrder;
        }

        m_pHeaderCurrent->Select(nOrder);

        if(nID==0)
        {
            //Resort(-1, (Qt::SortOrder)nOrder);
            setSortIndicator(nID, (Qt::SortOrder)nOrder);
        }
        else
        {
            setSortIndicator(nID, (Qt::SortOrder)nOrder);
        }



    }
    else
    {
        if(nID<(int)m_ListHeader.size())
        {
            m_pHeaderCurrent->Unselect();
            m_pHeaderCurrent = m_ListHeader[nID];

            m_pHeaderCurrent->Select(Qt::AscendingOrder);

            if(nID==0)
            {
                setSortIndicator(nID, Qt::AscendingOrder);
                //Resort(-1, Qt::AscendingOrder);
            }
            else
            {
                setSortIndicator(nID, Qt::AscendingOrder);
            }
        }

    }
}

bool HeaderType1::event(QEvent* event)
{
    int nEvent = 0;
    switch((int)event->type())
    {
        case QEvent::HoverEnter:
        {
            nEvent = 1;
        }
        break;

        case QEvent::HoverLeave:
        {
            nEvent = 2;
        }
        break;

        case QEvent::HoverMove:
        {
            nEvent = 3;
        }
        break;
    }





    return QHeaderView::event(event);
}

void HeaderType1::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
    int i=0;

    //painter->fillRect(rect, Qt::transparent);


    //QHeaderView::paintSection(painter, rect, logicalIndex);
    //return;

    QSize nSize = size();


    if(logicalIndex < (int)m_ListHeader.size())
    {
        m_ListHeader[logicalIndex]->show();
    }




    if(logicalIndex>=(int)m_ListHeader.size())
    {
        return;
    }

    if(rect.left()<0 && rect.right()>0)
    {
        for(i=0 ; i<logicalIndex ; i++)
        {
            m_ListHeader[i]->hide();
        }
    }
    else if(rect.left()<nSize.width() && rect.right()>nSize.width())
    {
        for(i=logicalIndex+1 ; i<(int)m_ListHeader.size() ; i++)
        {
            m_ListHeader[i]->hide();
        }
    }

    painter->fillRect(rect, QColor(21, 59, 68));

    if(logicalIndex==0)
    {
        //QHeaderView::paintSection(painter, rect, logicalIndex);



        QRect rectCenter = rect;

        rectCenter = QRect(rect.left()+5, rect.top()+1, rect.width()-10, rect.bottom()-2);

        m_ListHeader[logicalIndex]->setGeometry(rectCenter);
        m_ListHeader[logicalIndex]->show();
        //m_pType1->setGeometry(rectCenter);
        //m_pType1->show();

        QRect rectBorder;
        rectBorder = QRect(rect.right(), rect.top(), 1, rect.height());

        painter->fillRect(rectBorder, QColor(0, 0, 0));
    }
    else
    {
        //QHeaderView::paintSection(painter, rect, logicalIndex);

        //QHeaderView::paintSection(painter, rect, logicalIndex);

        QRect rectCenter = rect;

        rectCenter = QRect(rect.left()+5, rect.top()+1, rect.width()-10, rect.bottom()-2);

        m_ListHeader[logicalIndex]->setGeometry(rectCenter);
        m_ListHeader[logicalIndex]->show();

        //m_pType2->setGeometry(rectCenter);
        //m_pType2->show();

        QRect rectBorder;
        rectBorder = QRect(rect.right()-1, rect.top(), 3, rect.height());
        //rectBorder = QRect(rect.left(), rect.top(), 1, rect.height());

        painter->fillRect(rectBorder, QColor(0, 0, 0));
    }


}



void HeaderType1::SetOrderHeaderIndex(int nID)
{
    if(nID<(int)m_ListHeader.size())
    {
        m_pHeaderCurrent = m_ListHeader[nID];
    }
}

void HeaderType1::ChangeHeader(QStringList& list)
{
    ClearHeader();

    int i=0;
    for(i=0 ; i<list.size() ; i++)
    {
        FormHeaderType1* pHeaderType1 = new FormHeaderType1(this);
        pHeaderType1->SetID(i);

        QString strText = list[i];
        pHeaderType1->SetHeaderText(strText);

        connect(pHeaderType1, SIGNAL(Clicked(int)), this, SLOT(Clicked(int)));

        pHeaderType1->hide();
        pHeaderType1->Unselect();
        m_ListHeader.push_back(pHeaderType1);
    }

    m_pHeaderCurrent = m_ListHeader[0];
    //m_pHeaderCurrent->Select(Qt::AscendingOrder);

    update();
}

void HeaderType1::ClearHeader()
{
    int i=0;
    for(i=0 ; i<m_ListHeader.size() ; i++)
    {
        FormHeaderType1* pHeaderType1 = m_ListHeader[i];
        SAFE_DELETE(pHeaderType1);
    }

    m_ListHeader.clear();
    m_pHeaderCurrent = NULL;
}

int HeaderType1::GetDisplayWidth()
{
    int nWidth = 0;
    int i=0;
    for(i=0 ; i<m_ListHeader.size() ; i++)
    {
        FormHeaderType1* pHeaderType1 = m_ListHeader[i];
        //nWidth += sectionSizeFromContents(i).width();
        nWidth += pHeaderType1->size().width()+10;
    }

    //nWidth = m_ListHeader[m_ListHeader.size()-1]->width() + m_ListHeader[m_ListHeader.size()-1]->x();


    return nWidth;
}


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

    //int nFontSize = 24;
    if(nDisplayType==SDISPLAY_1280X1024)
    {
        setStyleSheet(
                            "QHeaderView { border:none; border-bottom: 0px solid #153b44; background: transparent; min-height: 50px; max-height: 50px;}"

                            "QHeaderView::section:horizontal { border:none; border-right: 1px solid white; color: white; background: transparent ; padding-left: 10px; }"
                            "QHeaderView::section:horizontal:hover { background: rgb(0, 160, 230);}"
                            "QHeaderView::section:horizontal:pressed { background: rgb(0, 180, 255);}"
                            "QHeaderView::up-arrow { width: 23px; height: 12px; padding-right: 25px; image: url(://image/Arrow_top_2.png); subcontrol-position: center right; }"
                            "QHeaderView::down-arrow { width: 23px; height: 12px; padding-right: 25px; image: url(://image/Arrow_under_2.png); subcontrol-position: center right; }");

        m_pHeaderCurrent->resize(196, 50);
    }
    else if(nDisplayType==SDISPLAY_1920X1080)
    {
        setStyleSheet(
                            //"QTableWidget {background-color: transparent; border: none; outline: none; color:black;}"
                            //"QHeaderView { border:none; border-bottom: 3px solid rgb(0, 160, 230); background: rgb(57, 58, 60); min-height: 60px;}"
                            "QHeaderView { border:none; border-bottom: 0px solid #153b44; background: transparent; min-height: 60px;}"

                            "QHeaderView::section:horizontal { border:none; border-right: 1px solid white; color: white; background: transparent ; padding-left: 10px; }"
                            "QHeaderView::section:horizontal:hover { background: rgb(0, 160, 230);}"
                            "QHeaderView::section:horizontal:pressed { background: rgb(0, 180, 255);}"
                            "QHeaderView::up-arrow { width: 23px; height: 12px; padding-right: 25px; image: url(://image/Arrow_top_2.png); subcontrol-position: center right; }"
                            "QHeaderView::down-arrow { width: 23px; height: 12px; padding-right: 25px; image: url(://image/Arrow_under_2.png); subcontrol-position: center right; }");
        m_pHeaderCurrent->resize(196, 60);
    }
}


void HeaderType1::sectionResized(int logicalIndex, int oldSize, int newSize)
{
    qDebug() << logicalIndex << ": " << oldSize << ", " << newSize;

    if(m_bResizeEnable==false)
    {
        return;
    }

    // 1. 어떤 테이블을 업데이트할지 먼저 결정합니다.
    QString tableName;
    if (m_nListType == 0) { // Worklist
        tableName = "WorklistTableHeader";
    } else if (m_nListType == 1) { // History
        tableName = "HistoryTableHeader";
    } else {
        return; // 유효하지 않은 타입이면 아무 작업도 하지 않음
    }


    // 2. 이 업데이트 작업을 위한 지역 DB 인스턴스를 생성합니다.
    SUTIL::SDatabase db(QString("SectionResize_%1").arg(reinterpret_cast<quintptr>(this)));
    if (db.OpenDatabase("/home/birdhead/test.db") == 0) // 0이 성공
    {
        // 3. 파라미터 바인딩을 사용하는 안전한 쿼리를 작성합니다.
        //    (테이블 이름은 바인딩할 수 없으므로, 변수로 처리하는 것이 안전합니다)
        QString query = QString("UPDATE %1 SET DisplayWidth = ? WHERE DisplayIndex = ? AND Visible = 1;")
                          .arg(tableName);

        // 4. 값을 안전하게 파라미터로 전달합니다.
        QVariantList params;
        params << newSize << logicalIndex;

        // 5. 새로운 ExecuteNonQuery 함수를 호출합니다.
        db.ExecuteNonQuery(query, params);
    }
    else
    {
        qWarning() << "DB open failed for sectionResized update.";
    }

    // 6. DB 업데이트 후, CommonData의 모델을 다시 로드하여 UI에 변경사항을 반영합니다.
    //    (Init... 함수들은 이제 내부적으로 DB에 안전하게 접근합니다)
    CommonData* pCommonData = MainWindow::GetCommonData();
    if (m_nListType == 0) {
        pCommonData->InitWorklistIndex();
    } else if (m_nListType == 1) {
        pCommonData->InitHistoryIndex();
    }

    // GetDatabase/ReleaseDatabase 호출이 필요 없습니다.
    // 'db' 객체는 스코프가 끝나면 자동으로 소멸됩니다.
}

void HeaderType1::SetListType(int nType)
{
    m_nListType = nType;
}


void HeaderType1::InitHeader()
{
    if(m_pHeaderCurrent!=NULL)
    {

        m_pHeaderCurrent->Unselect();
    }

    m_pHeaderCurrent = m_ListHeader[0];
    //m_pHeaderCurrent->Select(Qt::AscendingOrder);

    if(m_nListType==0)
    {
        //setSortIndicator(-1, Qt::AscendingOrder);
    }
    else
    {
        //setSortIndicator(-1, Qt::AscendingOrder);
    }

}


void HeaderType1::SetResizeEnable(bool bEnable)
{
    m_bResizeEnable = bEnable;
}
