import QtQuick
import QtQuick.Layouts
import QtQuick.Controls.impl as I
import QtQuick.Templates as T

T.Button {
    id: control

    /**
     * Set true when the button is supposed to be displayed in e.g. a TextField.
     * You want to do this when this button is directly related to the TextField
     * and the primary and only action for the TextField.
     * Usually, you'd only want to display an icon in this button.
     * If true, automatically sets height, width and position.
     *
     * ```qml
     * TextField {
     *   placeholderText: "Search..."
     *   Button {
     *     icon.source: "qrc:/images/MagnifyingGlass.svg"
     *     isFieldButton: true
     *   }
     * }
     * ```
     */
    property bool isFieldButton: false


    height: isFieldButton ? parent.height : null
    icon.color: Colors.primaryContrast
    icon.height: 21
    icon.width: 21
    implicitHeight: Math.max(implicitBackgroundHeight + topInset + bottomInset, implicitContentHeight + topPadding + bottomPadding)
    implicitWidth: Math.max(implicitBackgroundWidth + leftInset + rightInset, implicitContentWidth + leftPadding + rightPadding)
    /**
     * Icon is slightly larger than Text, so we need to reduce the padding a
     * tiny bit to make sure all Buttons are still the same height.
     */
    padding: Dimensions.m - (icon.source.toString() === "" ? 0 : 1)
    x: isFieldButton ? parent.x + parent.width - width : null

    background: Rectangle {
        anchors.fill: parent
        border.color: Colors.interactive
        border.width: isFieldButton ? 1 : 0
        bottomLeftRadius: topLeftRadius
        color: !control.enabled ? Colors.disabled : !control.hovered ? Colors.primary : Colors.primaryLighter
        radius: Dimensions.radius
        topLeftRadius: isFieldButton ? 0 : radius
    }
    contentItem: I.IconLabel {
        color: !control.enabled ? Colors.disabledForeground : Colors.primaryContrast
        display: control.display
        font: control.font
        icon: control.icon
        mirrored: control.mirrored
        spacing: Dimensions.s
        text: control.text
    }

    MouseArea {
        id: mouseArea

        anchors.fill: parent
        cursorShape: Qt.PointingHandCursor

        onPressed: mouse => mouse.accepted = false
    }
}
