#include "TitleBar.h"
#include "ui_TitleBar.h"

#include <QDateTime>
#include <QLocale>
#include <QDebug>

#include "LanguageManager.h"
#include "ConfigManager.h"
#include "Globals.h"

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

    m_timer = new QTimer();
    initConnect();
    m_timer->setInterval(500);
    m_timer->start();

    m_timeZone = QTimeZone("Asia/Shanghai");

    ui->bluetooth_icon->setVisible(false);

    m_gun_num = ConfigManager::instance()->ccu_cfg().GUN_Numb;
    updateTime();
}

TitleBar::~TitleBar()
{
    delete ui;
}

void TitleBar::setTimeZone(const QTimeZone &timeZone)
{
    m_timeZone = timeZone;
}

void TitleBar::setTitle(const QString &title)
{
    if (title.isEmpty()) {
        ui->title->setVisible(false);
        ui->cur_time->setVisible(true);
    } else {
        ui->title->setVisible(true);
        ui->cur_time->setVisible(false);
    }

    ui->title->setText(title);
}

void TitleBar::setSettingsEnable(bool enable)
{
    ui->settings_icon->setEnabled(enable);
}

void TitleBar::setReturnEnable(bool enable)
{
    ui->return_icon->setEnabled(enable);
}

void TitleBar::setReturnVisible(bool visible)
{
    ui->return_icon->setVisible(visible);
}

void TitleBar::initConnect()
{
    connect(m_timer, &QTimer::timeout, this, &TitleBar::updateTime);
    connect(ui->settings_icon, &QToolButton::clicked, this, [this]() { emit showLogin(); });
    connect(ui->return_icon, &QToolButton::clicked, this, [this]() { emit signalReturn(); });
    connect(LanguageManager::instance(), &LanguageManager::languageChanged, this, [this]() { ui->retranslateUi(this); });
    connect(GLOBALS, &Globals::chargeGunBasicValueChanged, this, [this](const BASIC_INFO& info) {
        auto temp = info.BOX_temp / 10.0;
        ui->box_temp->setText(QString("%1°C").arg(QString::number(temp, 'f', 2)));
    });
}

void TitleBar::updateTime()
{
    QDateTime now = QDateTime::currentDateTimeUtc();
    // QDateTime zoneTime = now.toTimeZone(m_timeZone);
    ui->cur_time->setText(now.toString("yyyy-MM-dd HH:mm:ss"));
}

void TitleBar::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
}
