#include "fmp_home_p.h"
#include "fmp_home_navwindow.h"
#include <fmp_logger_i.h>
#include <ctkPluginContext.h>
#include <ctkServiceReference.h>
#include <QDebug>
#include <fmp_epay_i.h>
#include <fmp_settings_i.h>
#include "fmp_login.h"
#include "fmp_he_handlers.h"

FMPHomePrivate::FMPHomePrivate(FMPHome *q)
    : q_ptr(q),
      _isLogined(false),
      _userName(""),
      _errorMsg("")
{
}

FMPHomePrivate::~FMPHomePrivate()
{
    Uninit();
}

int FMPHomePrivate::Init()
{
    Q_Q(FMPHome);
    _settings = q->GetService<FMPSettingsInterface>(q->_ctx);
    _navWindow = new NavWindow(_settings);

    FMPStartEventHandler* handler = new FMPStartEventHandler(q->_ctx, q);

    _navWindow->show();
    connect(_navWindow, SIGNAL(menuBtnClicked(QString)), this, SLOT(onMenuBtnClicked(QString)));

    q->_inited = true;
    return FMP_SUCCESS;
}

int FMPHomePrivate::Uninit()
{
    Q_Q(FMPHome);

    // 关闭导航窗口
    if (!_navWindow) {
        _navWindow->close();
    }
    delete _navWindow;
    _navWindow = 0;

    q->_inited = false;
    return FMP_SUCCESS;
}

void FMPHomePrivate::StartPlugins(const QVariantList &pids)
{
    qDebug() << pids;
}

int FMPHomePrivate::login()
{
    FMPLogin loginWnd(_settings->GetString(FMP_INIKEY_LOGINSERVER),
                      _settings->GetString(FMP_INIKEY_LOGINSTOREID),
                      _settings->GetString(FMP_INIKEY_LOGINPARTNERID));
    loginWnd.exec();
    if(loginWnd.isLogined()) {
        _isLogined = true;
        _userName = loginWnd.userName();
        return FMP_SUCCESS;
    } else {
        _isLogined = false;
        return FMP_FAILURE;
    }
}

void FMPHomePrivate::onMenuBtnClicked(QString btnName)
{
    Q_Q(FMPHome);
    FMP_DEBUG_CTX(q->_ctx) << "Menu clicked: " << btnName;

    if(!_isLogined && btnName!="tool") {
        if(login() != FMP_SUCCESS) {
            return;
        }
    }

    if(btnName == "payment") {
        FMPePayInterface *e = q->GetService<FMPePayInterface>(q->_ctx);
        e->StartService();
    } else if(btnName == "tool") {
        qDebug() << "tool menu";
    }
}
