/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., Ltd.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include <QFocusEvent>
#include "mouseui.h"
#define STYLE_FONT_SCHEMA  "org.ukui.style"

MouseUI::MouseUI(QWidget *parent, Qt::WindowFlags f) : QWidget(parent, f)
{
    setAttribute(Qt::WA_DeleteOnClose);
    mVlayout = new QVBoxLayout(this);
    mVlayout->setMargin(0);
    mVlayout->setSpacing(40);
    initUI();
}

MouseUI::~MouseUI()
{
}

DoubleClickTestLabel::DoubleClickTestLabel()
{
    setAttribute(Qt::WA_DeleteOnClose);

    QSizePolicy pSizePolicy = this->sizePolicy();
    pSizePolicy.setHorizontalPolicy(QSizePolicy::Fixed);
    pSizePolicy.setVerticalPolicy(QSizePolicy::Fixed);
    this->setSizePolicy(pSizePolicy);

    setFixedSize(QSize(54, 28));
    setScaledContents(true);

    setPixmap(QPixmap(":/img/plugins/mouse/double-click-off.png"));

    mDoubleClickTestDbus = new QDBusInterface("org.ukui.ukcc.session",
                                              "/Mouse",
                                              "org.ukui.ukcc.session.Mouse",
                                              QDBusConnection::sessionBus(), this);

    if (!mDoubleClickTestDbus->isValid()) {
        qCritical() << "org.ukui.ukcc.session.KeyBoard DBus error:" << mDoubleClickTestDbus->lastError();
    }

    this->setToolTip(tr("double-click to test"));
}

DoubleClickTestLabel::~DoubleClickTestLabel()
{
}

void DoubleClickTestLabel::mouseDoubleClickEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
    int delay = mDoubleClickTestDbus->property("doubleClick").toInt();
    setPixmap(QPixmap(":/img/plugins/mouse/double-click-on.png"));
    QTimer::singleShot(delay, this, [=]{
        setPixmap(QPixmap(":/img/plugins/mouse/double-click-off.png"));
    });
}

void MyTextEdit::startCursor(void)
{
    this->setStyleSheet("background-color:transparent;border-width:0;border-style:outset");
    QFocusEvent fe(QEvent::FocusIn, Qt::MouseFocusReason);
    focusInEvent(&fe);
}

void MouseUI::settingForIntel()
{
    mWheelSpeedWidget->hide();
    mDoubleClickIntervalWidget->hide();
    mScrollDirectionWdiget->setFrameShape(QFrame::HLine);
    mMouseAccelerationWidget->hide();
}

void MouseUI::initUI()
{
    //鼠标
    SettingGroup *mouseFrame = new SettingGroup(this);
    mMouseTitleLabel = new TitleLabel(this);
    //~ contents_path /Mouse/Mouse
    mMouseTitleLabel->setText(tr("Mouse"));
    mMouseTitleLabel->setContentsMargins(16,0,0,0);
    setDominantHandFrame();
    setScrollDirectionFrame();
    setWheelSpeedFrame();
    setDoubleClickFrame();

    mouseFrame->insertWidget(0, mDominantHandWidget);
    mouseFrame->insertWidget(1, mDoubleClickIntervalWidget);
    mouseFrame->insertWidget(2, mWheelSpeedWidget);
    mouseFrame->insertWidget(3, mScrollDirectionWdiget);

    QVBoxLayout *mouseVLayout = new QVBoxLayout(this);
    mouseVLayout->setSpacing(8);
    mouseVLayout->setMargin(0);
    mouseVLayout->addWidget(mMouseTitleLabel);
    mouseVLayout->addWidget(mouseFrame);

    //指针
    SettingGroup *pointerFrame = new SettingGroup(this);
    mPointerTitleLabel = new TitleLabel(this);
    //~ contents_path /Mouse/Pointer
    mPointerTitleLabel->setText(tr("Pointer"));
    mPointerTitleLabel->setContentsMargins(16,0,0,0);
    setPointerSpeedFrame();
    setMouseAccelerationFrame();
    setPointerPositionFrame();
    setPointerSizeFrame();

    pointerFrame->insertWidget(0, mPointerSpeedWidget);
    pointerFrame->insertWidget(1, mMouseAccelerationWidget);
    pointerFrame->insertWidget(2, mPointerSizeWidet);
    pointerFrame->insertWidget(3, mPointerPositionWidget);

    QVBoxLayout *pointerVLayout = new QVBoxLayout(this);
    pointerVLayout->setSpacing(8);
    pointerVLayout->setMargin(0);
    pointerVLayout->addWidget(mPointerTitleLabel);
    pointerVLayout->addWidget(pointerFrame);

    //光标
    SettingGroup *cursorFrame = new SettingGroup(this);

    mCursorTitleLabel = new TitleLabel(this);
    //~ contents_path /Mouse/Text Cursor
    mCursorTitleLabel->setText(tr("Text Cursor"));
    mCursorTitleLabel->setContentsMargins(16,0,0,0);
    setBlinkCursorFrame();
    setCursorSpeedFrame();

    cursorFrame->insertWidget(0, mBlinkingCursorOnTextWidget);
    cursorFrame->insertWidget(1, mCursorSpeedWidget);

    QVBoxLayout *cursorVLayout = new QVBoxLayout(this);
    cursorVLayout->setSpacing(8);
    cursorVLayout->setMargin(0);
    cursorVLayout->addWidget(mCursorTitleLabel);
    cursorVLayout->addWidget(cursorFrame);

    mVlayout->addLayout(mouseVLayout);
    mVlayout->addLayout(pointerVLayout);
    mVlayout->addLayout(cursorVLayout);
    mVlayout->addStretch();
}

void MouseUI::setDominantHandFrame()
{
    /* dominant hand Frame Setting */

    //~ contents_path /Mouse/Main mouse button
    mDominantHandWidget = new RadioButtonWidget(tr("Main mouse button"), this, UkccFrame::Top);
    mDominantHandWidget->setObjectName("Main mouse button");
    mDominantHandLeftRadio = new QRadioButton(tr("Left key"), this);
    mDominantHandRightRadio = new QRadioButton(tr("Right key"), this);
    mDominantHandWidget->addButton(mDominantHandLeftRadio, 0);
    mDominantHandWidget->addButton(mDominantHandRightRadio, 1, true);

}

void MouseUI::setScrollDirectionFrame()
{
    /* dominant hand Frame Setting */

    //~ contents_path /Mouse/Scroll direction
    mScrollDirectionWdiget = new RadioButtonWidget(tr("Scroll direction"), this);
    mScrollDirectionWdiget->setObjectName("Scroll direction");
    mScrollDirectionForwardRadio = new QRadioButton(tr("Forward"), this);
    mScrollDirectionReverseRadio = new QRadioButton(tr("Reverse"), this);
    mScrollDirectionWdiget->addButton(mScrollDirectionForwardRadio, 0);
    mScrollDirectionWdiget->addButton(mScrollDirectionReverseRadio, 1, true);
}

void MouseUI::setWheelSpeedFrame()
{
    /* wheel speed Frame Setting */

    //~ contents_path /Mouse/Wheel speed
    mWheelSpeedWidget = new SliderWidget(tr("Wheel speed"), true, this);
    mWheelSpeedWidget->setObjectName("Wheel speed");
    mWheelSpeedWidget->setLeftText(tr("Slow"));
    mWheelSpeedWidget->setRightText(tr("Fast"));
    mWheelSpeedWidget->slider()->setSliderType(KSliderType::NodeSlider);
    mWheelSpeedWidget->slider()->setRange(1,10);
    mWheelSpeedWidget->slider()->setTickInterval(1);
    mWheelSpeedWidget->slider()->setPageStep(1);
    mWheelSpeedWidget->slider()->installEventFilter(this);
}

void MouseUI::setDoubleClickFrame()
{
    /* Double Click Interval time Frame Setting */

    //~ contents_path /Mouse/Double click speed
    mDoubleClickIntervalWidget = new SliderWidget(tr("Double click speed"), false, this, UkccFrame::Bottom);
    mDoubleClickIntervalWidget->setObjectName("Double click speed");
    mDoubleClickIntervalWidget->addHintText(tr("Double click the image on the right to test the double-click effect"));
    mDoubleClickIntervalWidget->setLeftText(tr("Slow"));
    mDoubleClickIntervalWidget->setRightText(tr("Fast"));
    mDoubleClickIntervalWidget->slider()->setSliderType(KSliderType::SmoothSlider);
    mDoubleClickIntervalWidget->slider()->setMinimum(170);
    mDoubleClickIntervalWidget->slider()->setMaximum(1000);
    mDoubleClickIntervalWidget->slider()->setSingleStep(100);
    mDoubleClickIntervalWidget->slider()->setPageStep(100);
    mDoubleClickIntervalWidget->slider()->installEventFilter(this);
    mDoubleClickIntervalWidget->insertWidget(5, new DoubleClickTestLabel());
}

void MouseUI::setPointerSpeedFrame()
{
    /* Pointer Speed Frame Setting */

    //~ contents_path /Mouse/Pointer move speed
    mPointerSpeedWidget = new SliderWidget(tr("Pointer move speed"), false, this, UkccFrame::Top);
    mPointerSpeedWidget->setObjectName("Pointer move speed");
    mPointerSpeedWidget->setLeftText(tr("Slow"));
    mPointerSpeedWidget->setRightText(tr("Fast"));
    mPointerSpeedWidget->slider()->setSliderType(KSliderType::SmoothSlider);
    mPointerSpeedWidget->slider()->setMinimum(100);
    mPointerSpeedWidget->slider()->setMaximum(1000);
    mPointerSpeedWidget->slider()->setSingleStep(50);
    mPointerSpeedWidget->slider()->setPageStep(50);
    mPointerSpeedWidget->slider()->installEventFilter(this);
}

void MouseUI::setMouseAccelerationFrame()
{
    /* Mouse Acceleration Frame Setting */
    //~ contents_path /Mouse/Enable mouse acceleration to improve pointer accuracy
    mMouseAccelerationWidget = new SwitchWidget(tr("Enable mouse acceleration to improve pointer accuracy"), this, UkccFrame::None);
    mMouseAccelerationWidget->setObjectName("Enable mouse acceleration to improve pointer accuracyn");
}

void MouseUI::setPointerPositionFrame()
{
    /* Pointer Position Frame Setting */
    //~ contents_path /Mouse/Show pointer position when pressing ctrl
    mPointerPositionWidget = new SwitchWidget(tr("Show pointer position when pressing ctrl"), this, UkccFrame::None);
    mPointerPositionWidget->setObjectName("Show pointer position when pressing ctrl");
}

void MouseUI::setPointerSizeFrame()
{
    /* Pointer Size Frame Setting */

    //~ contents_path /Mouse/Pointer size
    mPointerSizeWidet = new RadioButtonWidget(tr("Pointer size"), this, UkccFrame::Bottom);
    mPointerSizeWidet->setObjectName("Pointer size");
    mPointerSizeSmallRadio = new QRadioButton(tr("Small(recommend)"), this);
    if (setTextDynamic(mPointerSizeSmallRadio, tr("Small(recommend)"))) {
        mPointerSizeSmallRadio->setToolTip(tr("Small(recommend)"));
    };
    const QByteArray styleID(STYLE_FONT_SCHEMA);
    QGSettings *stylesettings = new QGSettings(styleID, QByteArray(), this);
    connect(stylesettings, &QGSettings::changed, this, [=](const QString &key){
        if (key == "systemFontSize" || key == "systemFont") {
            if (setTextDynamic(mPointerSizeSmallRadio, tr("Small(recommend)"))) {
                mPointerSizeSmallRadio->setToolTip(tr("Small(recommend)"));
            }
        }
    });

    mPointerSizeMediumRadio = new QRadioButton(tr("Medium"), this);
    mPointerSizeLargeRadio = new QRadioButton(tr("Large"), this);
    mPointerSizeSmallRadio->setProperty("pointer", "Small");
    mPointerSizeMediumRadio->setProperty("pointer", "Medium");
    mPointerSizeLargeRadio->setProperty("pointer", "Large");
    mPointerSizeWidet->addButton(mPointerSizeSmallRadio, SMALLPOINTER);
    mPointerSizeWidet->addButton(mPointerSizeMediumRadio, MEDIUMPOINTER);
    mPointerSizeWidet->addButton(mPointerSizeLargeRadio, LARGEPOINTER, true);
}

bool MouseUI::setTextDynamic(QRadioButton *button, QString string)
{
    bool isOverLength = false;
    QFontMetrics fontMetrics(button->font());
    int labelValueSize = 150;
    int fontSize = fontMetrics.width(string);
    QString str = string;
    qDebug() << "fontSize:" << fontSize << ";labelValueSize:" << labelValueSize;
    if (fontSize > labelValueSize) {
        str = fontMetrics.elidedText(string, Qt::ElideRight, labelValueSize);
        isOverLength = true;
    } else {

    }
    button->setText(str);
    return isOverLength;
}

void MouseUI::setBlinkCursorFrame()
{
    /* Blinking Cursor On Text Frame Setting */
    //~ contents_path /Mouse/Text cursor flashing
    mBlinkingCursorOnTextWidget = new SwitchWidget(tr("Text cursor flashing"), this, UkccFrame::Top);
    mBlinkingCursorOnTextWidget->setObjectName("Text cursor flashing");
}

void MouseUI::setCursorSpeedFrame()
{
    /* Cursor Speed Frame Setting */

    //~ contents_path /Mouse/Cursor flashing frequency
    mCursorSpeedWidget = new SliderWidget(tr("Cursor flashing frequency"), false, this, UkccFrame::Bottom);
    mCursorSpeedWidget->setObjectName("Cursor flashing frequency");
    mCursorSpeedWidget->setLeftText(tr("Slow"));
    mCursorSpeedWidget->setRightText(tr("Fast"));
    mCursorSpeedWidget->slider()->setSliderType(KSliderType::SmoothSlider);
    mCursorSpeedWidget->slider()->setMinimum(100);
    mCursorSpeedWidget->slider()->setMaximum(2500);
    mCursorSpeedWidget->slider()->setSingleStep(200);
    mCursorSpeedWidget->slider()->setPageStep(200);

    MyTextEdit *cursorSpeedView = new MyTextEdit();
    cursorSpeedView->setPlaceholderText("Abc");
    cursorSpeedView->setEnabled(false);
    cursorSpeedView->startCursor();
    cursorSpeedView->setFixedWidth(48);
    mCursorSpeedWidget->insertWidget(5, cursorSpeedView);

    mCursorSpeedWidget->installEventFilter(this);
}
