// Copyright Mirage authors & contributors <https://github.com/mirukana/mirage>
// SPDX-License-Identifier: LGPL-3.0-or-later

import QtQuick 2.12
import QtQuick.Layouts 1.12
import QtQuick.Window 2.12
import Clipboard 0.1
import "../../.."
import "../../../Base"
import "../../../PythonBridge"
import "../../../ShortcutBundles"

Rectangle {

    readonly property alias historyList: historyList

    color: theme.chat.eventList.background

    HShortcut {
        sequences: window.settings.Keys.Messages.unfocus_or_deselect
        onActivated: {
            historyList.selectedCount ?
            historyList.checked = {} :
            historyList.currentIndex = -1
        }
    }

    HShortcut {
        sequences: window.settings.Keys.Messages.previous
        onActivated: historyList.focusPreviousMessage()
    }

    HShortcut {
        sequences: window.settings.Keys.Messages.next
        onActivated: historyList.focusNextMessage()
    }

    HShortcut {
        active: historyList.currentItem
        sequences: window.settings.Keys.Messages.select
        onActivated: historyList.toggleCheck(historyList.currentIndex)
    }

    HShortcut {
        active: historyList.currentItem
        sequences: window.settings.Keys.Messages.select_until_here
        onActivated:
            historyList.checkFromLastToHere(historyList.currentIndex)
    }

    HShortcut {
        sequences: window.settings.Keys.Messages.open_links_files
        onActivated: {
            const indice =
                historyList.getFocusedOrSelectedOrLastMediaEvents(true)

            for (const i of Array.from(indice).sort().reverse()) {
                const event = historyList.model.get(i)

                for (const url of JSON.parse(event.links)) {
                    utils.getLinkType(url) === Utils.Media.Image ?
                    historyList.openImageViewer(event, url) :
                    Qt.openUrlExternally(url)
                }
            }
        }
    }

    HShortcut {
        sequences: window.settings.Keys.Messages.open_links_files_externally
        onActivated: {
            const indice =
                historyList.getFocusedOrSelectedOrLastMediaEvents(true)

            for (const i of Array.from(indice).sort().reverse()) {
                const event = historyList.model.get(i)

                for (const url of JSON.parse(event.links))
                    Qt.openUrlExternally(url)
            }
        }
    }

    HListView {
        id: historyList

        property bool ownEventsOnLeft: false

        property string delegateWithSelectedText: ""
        property string selectedText: ""

        property bool showFocusedSeenTooltips: false

        property alias cursorShape: cursorShapeArea.cursorShape

        function focusCenterMessage() {
            const previous     = highlightRangeMode
            highlightRangeMode = HListView.NoHighlightRange
            currentIndex       = indexAt(0, contentY + height / 2)
            highlightRangeMode = previous
        }

        function focusPreviousMessage() {
            currentIndex === -1 && visibleEnd.y < contentHeight - height / 4 ?
            focusCenterMessage() :
            incrementCurrentIndex()
        }

        function focusNextMessage() {
            currentIndex === -1 && visibleEnd.y < contentHeight - height / 4 ?
            focusCenterMessage() :

            historyList.currentIndex === 0 ?
            historyList.currentIndex = -1 :

            decrementCurrentIndex()
        }

        function copySelectedDelegates() {
            if (historyList.selectedText) {
                Clipboard.text = historyList.selectedText
                return
            }

            if (! historyList.selectedCount && historyList.currentIndex !== -1) {
                const model  = historyList.model.get(historyList.currentIndex)
                const source = JSON.parse(model.source)

                Clipboard.text =
                    model.media_http_url &&
                    utils.isEmptyObject(JSON.parse(model.media_crypt_dict)) ?
                    model.media_http_url :

                    "body" in source ?
                    source.body :

                    utils.stripHtmlTags(utils.processedEventText(model))

                return
            }

            const contents = []

            for (const model of historyList.getSortedChecked()) {
                const source = JSON.parse(model.source)

                contents.push(
                    model.media_http_url &&
                    utils.isEmptyObject(JSON.parse(model.media_crypt_dict)) ?
                    model.media_http_url :

                    "body" in source ?
                    source.body :

                    utils.stripHtmlTags(utils.processedEventText(model))
                )
            }

            Clipboard.text = contents.join("\n\n")
        }

        function canDayBreak(item, itemAfter) {
            if (! item || ! itemAfter || ! item.date || ! itemAfter.date)
                return false

            return item.date.getDate() !== itemAfter.date.getDate()
        }

        function getFocusedOrSelectedOrLastMediaEvents(acceptLinks=false) {
            if (historyList.selectedCount) return historyList.checkedIndice
            if (historyList.currentIndex !== -1) return [historyList.currentIndex]

            // Find most recent event that's a media or contains links
            for (let i = 0; i < historyList.model.count && i <= 1000; i++) {
                const ev    = historyList.model.get(i)
                const links = JSON.parse(ev.links)

                if (ev.media_url || (acceptLinks && links.length)) return [i]
            }
        }

        anchors.fill: parent
        clip: true
        keyNavigationWraps: false
        leftMargin: theme.spacing
        rightMargin: theme.spacing
        topMargin: theme.spacing
        bottomMargin: theme.spacing

        // model: ModelStore.get(chat.userRoomId[0], chat.userRoomId[1], "events")
        model: []
        delegate: HistoryDelegate {}

        highlight: Rectangle {
            color: theme.chat.message.focusedHighlight
            opacity: theme.chat.message.focusedHighlightOpacity
        }

        MouseArea {
            id: cursorShapeArea
            anchors.fill: parent
            acceptedButtons: Qt.NoButton
        }

    }
}
