#include "select_ppd_dialog.h"
#include "ui_select_ppd_dialog.h"
#include "find_and_match_ppds.h"
#include "base_notify_dialog.h"
#include <QToolTip>
#include "custom_message_box.h"
#include "size_para.h"


SelectPpdDialog::SelectPpdDialog(QWidget *parentWindow ,QDialog *parent)
    : QDialog(parent)
    , m_ui(new Ui::SelectPpdDialog)
    , m_ppdMap(new ppdPrinterMap)
    , m_updateFailed(false)
    , m_currentChoosenPPD("")
    , m_currentChoosenModel("")
    , m_pParentWindow(parentWindow)
{
    setWindowModality(Qt::ApplicationModal);
    setWindowFlags(Qt::Tool);
    UKUI_WIN_CONTROL_PROTOOL(this);

    m_ui->setupUi(this);
    m_ui->titleBar->setTitleName(tr("Printer Driver"));
    m_ui->WindowBtn->setShowBtnsMode(QuadBtnsShowMode::ONLY_CLOSE_BTN,this);

    //厂商表
    m_vendorModal = new QStandardItemModel;
    m_vendorModal->invisibleRootItem();
    m_vendorModal->setColumnCount(1);

    m_ui->venderListView->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_ui->venderListView->setModel(m_vendorModal);
    m_ui->venderListView->setAlternatingRowColors(true);

    connect(m_ui->venderListView, SIGNAL(clicked(QModelIndex)),
            this, SLOT(venderListClicked(QModelIndex)));

    //型号表
    m_modelModal = new QStandardItemModel;
    m_modelModal->invisibleRootItem();
    m_modelModal->setColumnCount(1);

    m_ui->modelListView->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_ui->modelListView->setModel(m_modelModal);
    m_ui->modelListView->setAlternatingRowColors(true);

    connect(m_ui->modelListView, SIGNAL(clicked(QModelIndex)),
            this, SLOT(modelListClicked(QModelIndex)));
    connect(m_ui->modelListView, SIGNAL(entered(QModelIndex)),
            this, SLOT(modelListShowToolTip(QModelIndex)));

    connect(m_ui->cancelBtn,SIGNAL(clicked(bool)),this,SLOT(cancelAndClose()));
    connect(m_ui->applyBtn,SIGNAL(clicked(bool)),this,SLOT(sendOutPPDName()));

    QPoint temp = QPoint(parentWindow->mapToGlobal(QPoint(0,0)).x() + parentWindow->width()/2,parentWindow->mapToGlobal(QPoint(0,0)).y() + parentWindow->height()/2);
    this->move(temp - this->rect().center());
    this->setBackgroundRole(QPalette::Base);
}
SelectPpdDialog::~SelectPpdDialog()
{
    emit userCanceled();
    delete m_ui;
    delete m_ppdMap;
}

void SelectPpdDialog::onShow()
{
    QPoint temp = QPoint(m_pParentWindow->mapToGlobal(QPoint(0,0)).x() + m_pParentWindow->width()/2,m_pParentWindow->mapToGlobal(QPoint(0,0)).y() + m_pParentWindow->height()/2);
    this->move(temp - this->rect().center());
    this->setBackgroundRole(QPalette::Base);
    qDebug()<<"Set SelectPpdDialog to toplevel.";
    if(!isActiveWindow())
    {
        hide();
        show();
        updateTableView();
    }
    show();
    raise();
    activateWindow();
}

void SelectPpdDialog::updateTableView()
{
    if((g_findAndMatchWorkThread->hasPPDsMap() == true) && (g_findAndMatchWorkThread->isBusy() == false))
    {
        delete m_ppdMap;
        m_ppdMap = new ppdPrinterMap();
        g_findAndMatchWorkThread->getCurrentPPDsMap(*m_ppdMap);
    }
    else
    {
        BaseNotifyDialog *waitDialog = new BaseNotifyDialog(this);
        waitDialog->dialogSetType(BaseNotifyDialogType::WAITTING);
        waitDialog->labelSetText(tr("Reading Drivers，Please Wait..."));//正在读取驱动，请稍后…

        m_updateFailed = true;
        delete m_ppdMap;
        m_ppdMap = new ppdPrinterMap();
        g_findAndMatchWorkThread->updatePPDsMap();

        connect(g_findAndMatchWorkThread,&FindAndMatchPPDs::updateFinished,this,[&](){
            qDebug() << "更新完毕";
            m_updateFailed = false;
            g_findAndMatchWorkThread->getCurrentPPDsMap(*m_ppdMap);
            emit waitDialog->closeThis();
        });
        connect(g_findAndMatchWorkThread,&FindAndMatchPPDs::updateFailed,this,[&](){
            qDebug() << "更新失败";
            m_updateFailed = true;
            emit waitDialog->closeThis();
        });

        waitDialog->showThis();
        if(m_updateFailed)
        {
            qDebug() << "无法取得ppd的Map，退出窗口";
            return;
        }
    }

    ppdPrinterMap::iterator vendorName;

    m_vendorModal->clear();
    int i = 0;
    for(vendorName = m_ppdMap->begin();vendorName != m_ppdMap->end();vendorName++,i++)
    {
        QStandardItem *currentVendorName = new QStandardItem(QString(vendorName.key()));
        currentVendorName->setFont(m_font);
        m_vendorModal->setItem(i,0,currentVendorName);
    }
}

void SelectPpdDialog::venderListClicked(const QModelIndex &index)
{
    QStandardItem *item = m_vendorModal->itemFromIndex(index);

    ppdPrinterMap::iterator vendorName;
    QString currentVendorName = item->text();

    m_currentVendor.clear();
    vendorName = m_ppdMap->find(currentVendorName);
    if(vendorName != m_ppdMap->end())
    {
        m_currentVendor = vendorName.value();
    }

    QMap<QString,PPDsAndAttr>::iterator ppdName;
    int i = 0;
    m_modelModal->clear();
    m_currentChoosenModel.clear();
    for(ppdName = m_currentVendor.begin();ppdName != m_currentVendor.end();ppdName++,i++)
    {
        QString showText = QString(ppdName.value().ppd_make_and_model);

        QStandardItem *currentModelName = new QStandardItem(showText);
        currentModelName->setFont(m_font);
        m_modelModal->setItem(i,0,currentModelName);
    }
}

void SelectPpdDialog::modelListClicked(const QModelIndex &index)
{
    QStandardItem *item = m_modelModal->itemFromIndex(index);

    QMap<QString,PPDsAndAttr>::iterator ppdName;
    for(ppdName = m_currentVendor.begin();ppdName != m_currentVendor.end();ppdName++)
    {
        if (item->text() == QString(ppdName.value().ppd_make_and_model))
        {
            m_currentChoosenPPD.clear();
            m_currentChoosenPPD = QString(ppdName.value().ppdname);
            m_currentChoosenModel.clear();
            m_currentChoosenModel = QString(ppdName.value().ppd_make_and_model);
        }
    }
}

void SelectPpdDialog::modelListShowToolTip(const QModelIndex &index)
{
    if (!index.isValid())
    {
        qDebug() << "Invalid index";
        return;
    }

    QToolTip::showText(QCursor::pos(), index.data().toString());
}

void SelectPpdDialog::sendOutPPDName()
{
    if(!m_currentChoosenPPD.isEmpty() && !m_currentChoosenModel.isEmpty())
    {
        qDebug() << "选中的厂商为：" << m_currentChoosenModel;
        qDebug() << "选中的型号为：" << m_currentChoosenPPD;
        emit chosenPPDName(m_currentChoosenPPD);
        this->close();
        return;
    }
    else
    {
        QString warningMsg = tr("Please Choose Model And Vender!");
        CustomMessageBox Msg(CustomMessageBox::Warning,tr("Warning"),warningMsg,CustomMessageBox::NoButton);
        Msg.setParent(this);
        Msg.addButton(tr("Close"), CustomMessageBox::NoRole);
        Msg.exec();
        return;
    }
}

void SelectPpdDialog::cancelAndClose()
{
    qDebug() << "用户取消";
    this->close();
}

void SelectPpdDialog::setFontSizeF(QFont ft)
{
    m_font = ft;
    m_ui->titleBar->setFont(m_font);
    for (int i = 0; i < m_vendorModal->rowCount(); ++i)
    {
        m_vendorModal->item(i,0)->setFont(m_font);
    }
    for (int i = 0; i < m_modelModal->rowCount(); ++i)
    {
        m_modelModal->item(i,0)->setFont(m_font);
    }
}
