import QtQuick 2.12
import QtQuick.Controls 2.12

import Controls 1.0 as Controls
import Utils 1.0

ComboBox {
    id: control

    leftPadding: 16
    rightPadding: 16

    delegate: ItemDelegate {
        width: control.width
        leftPadding: control.leftPadding
        clip: true

        contentItem: Text {
            text: modelData
            color: pressed ? Palette.selectedTextColor : Palette.textColor
            font: control.font
            elide: Text.ElideRight
            verticalAlignment: Text.AlignVCenter
        }

        background: Rectangle {
            color: control.currentIndex === index ?
                       Palette.selectedBackgroundColor :
                       (highlighted ? Palette.hoveredBackgroundColor : Palette.backgroundColor)
        }

        highlighted: control.highlightedIndex === index
    }

    indicator: Canvas {
        id: canvas
        x: control.width - width - control.rightPadding
        y: control.topPadding + (control.availableHeight - height) / 2
        width: 8
        height: 5
        contextType: "2d"

        Connections {
            target: control
            onDownChanged: canvas.requestPaint()
        }

        onPaint: {
            context.reset();

            if (control.down) {
                context.moveTo(0, height);
                context.lineTo(width, height);
                context.lineTo(width / 2, 0);
            } else {
                context.moveTo(0, 0);
                context.lineTo(width, 0);
                context.lineTo(width / 2, height);
            }

            context.closePath();
            context.fillStyle = control.down ? Palette.selectedTextColor : Palette.textColor;
            context.fill();
        }
    }

    contentItem: Text {
        rightPadding: control.indicator.width + 8

        text: control.displayText
        font: control.font
        color: control.down ? Palette.selectedTextColor : Palette.textColor
        elide: Text.ElideRight
        verticalAlignment: Text.AlignVCenter
    }

    background: Rectangle {
        implicitWidth: 120
        implicitHeight: 46
        color: control.down ? Palette.selectedBackgroundColor : Palette.backgroundColor
        border.color: Palette.borderColor
        border.width: 1
        radius: 5
    }

    popup: Popup {
        y: control.height + 2
        width: control.width
        implicitHeight: contentItem.implicitHeight
        padding: 1

        contentItem: ListView {
            clip: true
            implicitHeight: contentHeight
            model: control.popup.visible ? control.delegateModel : null
            currentIndex: control.highlightedIndex

            ScrollBar.vertical: Controls.ScrollBar {}
        }

        background: Rectangle {
            color: Palette.backgroundColor
            border.color: Palette.borderColor
            border.width: 1
            radius: 5
        }
    }
}
