// file: poc-qt/poc003/qml/main.qml

import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import QtMultimedia

ApplicationWindow {
    visible: true
    width: 960
    height: 700
    title: "POC003 - Webcam Preview"

    MediaDevices {
        id: mediaDevices
    }

    Camera {
        id: camera
        cameraDevice: mediaDevices.defaultVideoInput
    }

    CaptureSession {
        id: captureSession
        camera: camera
        videoOutput: videoOutput
    }

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: 12
        spacing: 8

        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "black"
            border.width: 1
            border.color: "#555"

            VideoOutput {
                id: videoOutput
                anchors.fill: parent
                fillMode: VideoOutput.PreserveAspectFit
            }
        }

        RowLayout {
            Layout.fillWidth: true
            spacing: 8

            Button {
                text: camera.active ? "Stop camera" : "Start camera"
                onClicked: {
                    camera.active = !camera.active
                }
            }

            Button {
                text: "Restart"
                onClicked: {
                    camera.stop()
                    camera.start()
                }
            }

            Label {
                Layout.fillWidth: true
                text: mediaDevices.videoInputs.length > 0
                    ? ("Camera: " + camera.cameraDevice.description)
                    : "No camera detected"
                wrapMode: Text.WrapAnywhere
            }
        }

        Label {
            Layout.fillWidth: true
            text: "Detected cameras: " + mediaDevices.videoInputs.length
        }

        ListView {
            Layout.fillWidth: true
            Layout.preferredHeight: 120
            clip: true
            model: mediaDevices.videoInputs

            delegate: Rectangle {
                width: ListView.view.width
                height: 32
                color: camera.cameraDevice.id === modelData.id ? "#334" : "transparent"

                Text {
                    anchors.verticalCenter: parent.verticalCenter
                    anchors.left: parent.left
                    anchors.leftMargin: 8
                    text: modelData.description
                    color: "white"
                }

                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        camera.stop()
                        camera.cameraDevice = modelData
                        camera.start()
                    }
                }
            }
        }
    }

    Component.onCompleted: {
        if (mediaDevices.videoInputs.length > 0) {
            camera.start()
        }
    }
}
