/*
 * Copyright (c) 2014-2025 Meltytech, LLC
 *
 * 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 3 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, see <http://www.gnu.org/licenses/>.
 */
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import Shotcut.Controls as Shotcut
import org.shotcut.qml as Shotcut

Rectangle {
    id: filterWindow

    signal filterSelected(int index)

    function open() {
        filterWindow.visible = true;
        searchField.focus = true;
    }

    function close() {
        filterWindow.visible = false;
        searchField.text = '';
        searchField.focus = false;
    }

    visible: false
    onVisibleChanged: {
        switch (metadatamodel.filter) {
        case Shotcut.MetadataModel.FavoritesFilter:
            favButton.checked = true;
            break;
        case Shotcut.MetadataModel.VideoFilter:
            vidButton.checked = true;
            if (metadatamodel.search === '#color') {
                vidButton.text = colorMenuItem.text;
                vidButton.videoFilterType = 'color';
            }
            break;
        case Shotcut.MetadataModel.AudioFilter:
            audButton.checked = true;
            break;
        case Shotcut.MetadataModel.LinkFilter:
            lnkButton.checked = true;
            break;
        case Shotcut.MetadataModel.FilterSetFilter:
            setButton.checked = true;
            break;
        }
    }
    color: activePalette.window

    SystemPalette {
        id: activePalette
    }

    ColumnLayout {
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.margins: 8

        RowLayout {
            id: searchBar

            property var savedFilter

            Layout.fillWidth: true

            TextField {
                id: searchField

                Layout.fillWidth: true
                focus: true
                placeholderText: qsTr("search")
                selectByMouse: true
                onTextChanged: {
                    if (length !== 1 && text !== metadatamodel.search)
                        metadatamodel.search = text;
                    if (length > 0) {
                        parent.savedFilter = typeGroup.checkedButton;
                        favButton.checked = vidButton.checked = audButton.checked = false;
                    } else {
                        parent.savedFilter.checked = true;
                    }
                }
                Keys.onReturnPressed: event => {
                    if (menuListView.currentIndex >= 0) {
                        menuListView.itemSelected(menuListView.currentIndex);
                    } else {
                        menuListView.selectNext();
                    }
                    event.accepted = true;
                }
                Keys.onEnterPressed: event => Keys.onReturnPressed(event)
                Keys.onEscapePressed: {
                    if (text !== '')
                        text = '';
                    else
                        filterWindow.close();
                }
                Keys.onUpPressed: menuListView.selectPrevious()
                Keys.onDownPressed: menuListView.selectNext()
            }

            ToolButton {
                id: clearButton

                padding: 2
                implicitWidth: 20
                implicitHeight: 20
                icon.name: 'edit-clear'
                icon.source: 'qrc:///icons/oxygen/32x32/actions/edit-clear.png'
                hoverEnabled: true
                onClicked: searchField.text = ''

                Shotcut.HoverTip {
                    text: qsTr('Clear search')
                }
            }

            Label {
                width: 10
            }

            Shotcut.Button {
                id: closeButton

                icon.name: 'window-close'
                icon.source: 'qrc:///icons/oxygen/32x32/actions/window-close.png'
                padding: 2
                implicitWidth: 20
                implicitHeight: 20
                onClicked: filterWindow.close()

                Shotcut.HoverTip {
                    text: qsTr('Close menu')
                }
            }

            Label {
                width: 40
            }
        }

        RowLayout {
            id: toolBar

            Layout.fillWidth: true

            ButtonGroup {
                id: typeGroup
            }

            Shotcut.ToggleButton {
                id: favButton

                checked: true
                implicitWidth: 80
                icon.name: 'bookmarks'
                icon.source: 'qrc:///icons/oxygen/32x32/places/bookmarks.png'
                text: qsTr('Favorite')
                display: AbstractButton.TextBesideIcon
                ButtonGroup.group: typeGroup
                onClicked: {
                    if (checked) {
                        metadatamodel.filter = Shotcut.MetadataModel.FavoritesFilter;
                        metadatamodel.search = '';
                        searchField.text = '';
                        checked = true;
                    }
                }

                Shotcut.HoverTip {
                    text: qsTr('Show favorite filters')
                }
            }

            RowLayout {
                spacing: 0

                Shotcut.ToggleButton {
                    id: vidButton

                    property string videoFilterType: 'video'

                    implicitWidth: 80
                    icon.name: 'video-television'
                    icon.source: 'qrc:///icons/oxygen/32x32/devices/video-television.png'
                    text: qsTr('Video')
                    ButtonGroup.group: typeGroup
                    background: Rectangle {
                        topLeftRadius: 3
                        bottomLeftRadius: 3
                        color: vidButton.checked ? activePalette.highlight : activePalette.button
                        border.color: activePalette.shadow
                        border.width: vidButton.checked ? 0 : 1
                    }
                    onClicked: {
                        if (checked) {
                            searchField.text = '';
                            if (videoFilterType === 'video') {
                                metadatamodel.filter = Shotcut.MetadataModel.VideoFilter;
                                metadatamodel.search = '';
                            } else if (videoFilterType === 'gpu') {
                                metadatamodel.filter = Shotcut.MetadataModel.GPUFilter;
                                metadatamodel.search = '';
                            } else if (videoFilterType === '10bit') {
                                metadatamodel.filter = Shotcut.MetadataModel.VideoFilter;
                                metadatamodel.search = '#10bit';
                            } else if (videoFilterType === 'color') {
                                metadatamodel.filter = Shotcut.MetadataModel.VideoFilter;
                                metadatamodel.search = '#color';
                            } else if (videoFilterType === 'rgba') {
                                metadatamodel.filter = Shotcut.MetadataModel.VideoFilter;
                                metadatamodel.search = '#rgba';
                            } else if (videoFilterType === 'yuv') {
                                metadatamodel.filter = Shotcut.MetadataModel.VideoFilter;
                                metadatamodel.search = '#yuv';
                            }
                            checked = true;
                        }
                    }

                    Shotcut.HoverTip {
                        text: qsTr('Show video filters')
                    }
                }

                Shotcut.ToolButton {
                    id: vidMenuButton

                    implicitWidth: 22
                    implicitHeight: vidButton.height
                    padding: 0
                    text: '▼'
                    onClicked: vidMenu.popup()
                    background: Rectangle {
                        topRightRadius: 3
                        bottomRightRadius: 3
                        color: vidButton.checked ? activePalette.highlight : activePalette.button
                        border.color: activePalette.shadow
                        border.width: vidButton.checked ? 0 : 1
                    }

                    Shotcut.HoverTip {
                        text: qsTr('Video filter options')
                    }

                    Menu {
                        id: vidMenu

                        MenuItem {
                            text: qsTr('All Video')
                            onTriggered: {
                                vidButton.videoFilterType = 'video';
                                vidButton.text = qsTr('Video');
                                vidButton.checked = true;
                                vidButton.clicked();
                            }
                        }

                        MenuItem {
                            text: qsTr('10-bit')
                            onTriggered: {
                                vidButton.videoFilterType = '10bit';
                                vidButton.text = text;
                                vidButton.checked = true;
                                vidButton.clicked();
                            }
                        }

                        MenuItem {
                            id: colorMenuItem
                            text: qsTr('Color')
                            onTriggered: {
                                vidButton.videoFilterType = 'color';
                                vidButton.text = text;
                                vidButton.checked = true;
                                vidButton.clicked();
                            }
                        }

                        MenuItem {
                            text: qsTr('GPU')
                            visible: settings.playerGPU
                            height: visible ? colorMenuItem.height : 0
                            onTriggered: {
                                vidButton.videoFilterType = 'gpu';
                                vidButton.text = text;
                                vidButton.checked = true;
                                vidButton.clicked();
                            }
                        }

                        MenuItem {
                            text: qsTr('RGBA')
                            onTriggered: {
                                vidButton.videoFilterType = 'rgba';
                                vidButton.text = text;
                                vidButton.checked = true;
                                vidButton.clicked();
                            }
                        }

                        MenuItem {
                            text: qsTr('YUV')
                            onTriggered: {
                                vidButton.videoFilterType = 'yuv';
                                vidButton.text = text;
                                vidButton.checked = true;
                                vidButton.clicked();
                            }
                        }
                    }
                }
            }

            Shotcut.ToggleButton {
                id: audButton

                implicitWidth: 80
                icon.name: 'speaker'
                icon.source: 'qrc:///icons/oxygen/32x32/actions/speaker.png'
                text: qsTr('Audio')
                ButtonGroup.group: typeGroup
                onClicked: {
                    if (checked) {
                        metadatamodel.filter = Shotcut.MetadataModel.AudioFilter;
                        metadatamodel.search = '';
                        searchField.text = '';
                        checked = true;
                    }
                }

                Shotcut.HoverTip {
                    text: qsTr('Show audio filters')
                }
            }

            Shotcut.ToggleButton {
                id: lnkButton

                implicitWidth: 80
                visible: attachedfiltersmodel.supportsLinks
                icon.name: 'chronometer'
                icon.source: 'qrc:///icons/oxygen/32x32/actions/chronometer.png'
                text: qsTr('Time')
                ButtonGroup.group: typeGroup
                onClicked: {
                    if (checked) {
                        metadatamodel.filter = Shotcut.MetadataModel.LinkFilter;
                        metadatamodel.search = '';
                        searchField.text = '';
                        checked = true;
                    }
                }

                Shotcut.HoverTip {
                    text: qsTr('Show time filters')
                }
            }

            Shotcut.ToggleButton {
                id: setButton

                implicitWidth: 80
                icon.name: 'server-database'
                icon.source: 'qrc:///icons/oxygen/32x32/places/server-database.png'
                text: qsTr('Sets')
                ButtonGroup.group: typeGroup
                onClicked: {
                    if (checked) {
                        metadatamodel.filter = Shotcut.MetadataModel.FilterSetFilter;
                        metadatamodel.search = '';
                        searchField.text = '';
                        checked = true;
                    }
                }

                Shotcut.HoverTip {
                    text: qsTr('Show filter sets')
                }
            }

            Item {
                Layout.fillWidth: true
            }
        }

        ScrollView {
            Layout.fillWidth: true
            Layout.preferredHeight: filterWindow.height - toolBar.height - searchBar.height - iconKeywordsRow.height - parent.spacing * (parent.children.length - 1)
            clip: true
            ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
            ScrollBar.horizontal.height: 0
            ScrollBar.vertical.policy: ScrollBar.AlwaysOn
            ScrollBar.vertical.visible: contentHeight > height
            ScrollBar.vertical.width: 16
            ScrollBar.vertical.contentItem: Rectangle {
                color: (palette.windowText.hsvValue > palette.window.hsvValue) ? Qt.lighter(palette.window, 2) : Qt.darker(palette.window)
                radius: width / 2
            }
            ScrollBar.vertical.background: Rectangle {
                color: parent.palette.alternateBase
            }

            ListView {
                id: menuListView

                function itemSelected(index) {
                    if (index > -1) {
                        filterSelected(index);
                        filterWindow.close();
                    }
                }

                function selectNext() {
                    do {
                        currentIndex = Math.min(currentIndex + 1, count - 1);
                    } while (currentItem !== null && !currentItem.visible && currentIndex < count - 1)
                }

                function selectPrevious() {
                    do {
                        menuListView.currentIndex = Math.max(menuListView.currentIndex - 1, 0);
                    } while (!menuListView.currentItem.visible && menuListView.currentIndex > 0)
                }

                anchors.fill: parent
                model: metadatamodel
                boundsBehavior: Flickable.StopAtBounds
                maximumFlickVelocity: 600
                currentIndex: -1
                focus: true
                onCountChanged: {
                    currentIndex = -1;
                }

                delegate: FilterMenuDelegate {}
            }
        }

        RowLayout {
            id: iconKeywordsRow

            Layout.preferredHeight: 60

            AnimatedImage {
                id: icon

                property var current: metadatamodel.get(menuListView.currentIndex)

                source: current ? (current.icon.toString().length ? current.icon : current.isAudio ? 'qrc:///icons/oxygen/32x32/actions/speaker.png' : current.type === Shotcut.Metadata.Link ? 'qrc:///icons/oxygen/32x32/actions/chronometer.png' : '') : ''
                asynchronous: true
                Layout.preferredWidth: parent.Layout.preferredHeight * sourceSize.width / sourceSize.height
                Layout.preferredHeight: parent.Layout.preferredHeight
                fillMode: Image.PreserveAspectFit
                onPlayingChanged: {
                    if (!playing)
                        playing = true;
                }
            }

            Label {
                id: keywordsLabel

                text: icon.current ? (icon.current.type === Shotcut.Metadata.FilterSet && icon.current.mlt_service.length === 0) ? qsTr('Delete a custom filter set by right-clicking it.') : icon.current.keywords : ''
                wrapMode: Text.WordWrap
                Layout.fillWidth: true
                Layout.alignment: Qt.AlignVCenter | Qt.AlignLeft
                Layout.preferredWidth: filterWindow.width - parent.Layout.preferredHeight - 20
            }
        }
    }
}
