#include "timelabel.h"
#include "QApplication"
#include <QDebug>
#include <QDateTime>

TimeLabel::TimeLabel(QWidget *parent) :
    KLabel(parent)
{
    QFont font = QApplication::font();
    if (QLocale::system().amText() == "སྔ་དྲོ་") {
        font.setPixelSize(font.pointSize() * 20 / 11);
    } else {
        font.setPixelSize(font.pointSize() * 28 / 11);
    }
    font.setWeight(QFont::Medium);
    font.setBold(true);
    this->setFont(font);
    this->setAlignment(Qt::AlignVCenter);
    this->setContentsMargins(0, 0, 0, 0);
    this->setObjectName("timeClockLable");
    timerID = startTimer(1000);

    areaInterface = new QDBusInterface("org.ukui.ukcc.session",
                                       "/Area",
                                       "org.ukui.ukcc.session.Area",
                                       QDBusConnection::sessionBus(),
                                       this);
    if (areaInterface) {
        timeFormat = areaInterface->property("timeFormat").toString();
    } else {
        if (!areaInterface->isValid()) {
            qCritical() << "org.ukui.ukcc.session.Area DBus error:" << areaInterface->lastError();
        }
    }
    setTimeText();
}

TimeLabel::~TimeLabel()
{
    killTimer(timerID);
}

void TimeLabel::timerEvent(QTimerEvent *e)
{
    if (e->timerId() == timerID) {
        setTimeText();
    }
}

void TimeLabel::setTimeText()
{
    QString currentsecStr;
    QDateTime datetime = QDateTime::currentDateTime();
    if (areaInterface->property("timeFormat").toString() == "24") {
        currentsecStr = datetime.toString("hh : mm : ss");
    } else {
        if (QLocale::system().amText() == QString("上午") || QLocale::system().amText() == QString("སྔ་དྲོ་")) {
            currentsecStr = datetime.toString("AP hh: mm : ss");
        } else {
            currentsecStr = datetime.toString("hh: mm : ss AP");
        }
    }
    QString dateString;
    if ("cn" == areaInterface->property("dateFormat").toString()) {
        dateString = datetime.toString("yyyy/MM/dd ddd").replace("周", "星期");
    } else {
        dateString = datetime.toString("yyyy-MM-dd ddd").replace("周", "星期");
    }
    if (dateString != date) {
        date = dateString;
        Q_EMIT dateChanged();
    }
    setText(currentsecStr);
}

QString TimeLabel::dateText()
{
    return date;
}
