import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Layouts 1.14
import QtQuick.Controls 2.14
import Qt.labs.qmlmodels 1.0
import QtQuick.Dialogs 1.3


Rectangle {
    id: tableBackground
    color: activePalette.dark
    width: table.width + 25
    implicitHeight: scene3d.height
    onVisibleChanged: {
        implicitWidth = table.width + 25
    }
    property var fullScreen: {
        // make sure the table.width adjust adaptively, in case exceeding tableBackground.width
        table.width = tableBackground.width - 25
        return timeline.fullScreen
    }
    property var defaultTableWidth: 400
    MouseArea {
        width: parent.width
        height: parent.height
        anchors.fill: parent
        acceptedButtons: Qt.LeftButton|Qt.MiddleButton|Qt.RightButton
        // do nothing, to cover the scene3D mouse_handler
        onPressed: {}
        onPositionChanged: {}
        onReleased: {}
        onWheel: {}
    }
    Rectangle {
        id: resizeHelper
        color: activePalette.dark
        width: 10
        height: parent.height
        MouseArea {
            anchors.fill: parent
            property real lastX: 0.0
            cursorShape: Qt.SizeAllCursor
            onPressed: {          
                lastX = mouseX
            }
            onPositionChanged: {
                var deltX = lastX - mouseX
                // tableBackground.table.width += deltX 
                tableBackground.x -= deltX
                // console.log("tableBackground.x:" + tableBackground.x)
            }
        }
    }
    Rectangle {
        id: resizeHelper2
        anchors.right: parent.right
        color: activePalette.dark
        width: 10
        height: parent.height
        MouseArea {
            anchors.fill: parent
            property real lastX: 0.0
            cursorShape: Qt.SizeHorCursor
            onPressed: {          
                lastX = mouseX
            }
            onPositionChanged: {
                var deltX = lastX - mouseX
                defaultTableWidth -= deltX
                table.width = defaultTableWidth
                tableBackground.width = table.width + 25 
                // console.log("tableBackground.width:" + tableBackground.width)
            }
        }
    }
    Column {
        id: root
        x: 10
        Layout.fillWidth: true
        Layout.alignment : Qt.AlignTop
        Layout.minimumWidth: 50
        Layout.preferredWidth: 400
        Layout.maximumWidth: 4000
    Rectangle {
        height: 5
        width: parent.width
        color: "transparent"
    }
    Row {
        id: toolBar
        z: 2
        height: 30
        spacing: 5
        DefaultButton {
            implicitWidth: 36
            implicitHeight: parent.height
            DefaultCheckBox {
                focusPolicy: Qt.NoFocus
                implicitHeight: parent.height
                checked: false
                indicator.height : 18
                indicator.width : 18
                // text: "<b><font color='white'>All</font></b>"
                nextCheckState: function() {
                    if (checkState == Qt.Unchecked) {
                        modelData.spreadSheetModel.allDisplayed = true
                        modelData.renderStateChanged()
                        return Qt.Checked
                    }
                    else {
                        modelData.spreadSheetModel.allDisplayed = false
                        modelData.renderStateChanged()
                        return Qt.Unchecked
                    }
                }
                ToolTip {
                    visible: parent.hovered
                    delay: 500
                    text: qsTr("Select All")
                }
            }
        }
        DefaultToolButton {
            focusPolicy: Qt.NoFocus
            implicitWidth: 30
            implicitHeight: 30
            icon.source: "file:png/export.png"
            onClicked: {
                fileDialog.open()
            }
            FileDialog {
                id: fileDialog
                title: "Please choose export file"
                selectExisting: false
                // folder: Qt.resolvedUrl("../csv/")
                nameFilters: ["CSV files (*.csv)"]
                onAccepted: {
                    if(modelData.spreadSheetModel.exportPointsInformation(fileDialog.fileUrl)) {
                        console.log("Succeed to export: " + fileDialog.fileUrl)
                    } else {
                        console.log("Unable to export: " + fileDialog.fileUrl)
                        messageDialog.setText("Unable to export: \n" + fileDialog.fileUrl)
                        messageDialog.open()
                    }
                        
                }
            }
            ToolTip {
                visible: parent.hovered
                delay: 500
                text: qsTr("Export Points Info")
            }
        }
        DefaultToolButton {
            focusPolicy: Qt.NoFocus
            implicitWidth: 30
            implicitHeight: 30
            icon.source: "file:png/save.png"
            onClicked: {
                modelData.spreadSheetModel.saveCurrentColumnNames()
            }
            ToolTip {
                visible: parent.hovered
                delay: 500
                text: qsTr("Save Column Order")
            }
        }
        Text {
            anchors.verticalCenter: parent.verticalCenter
            color: activePalette.text
            text: "Points: " + modelData.spreadSheetModel.rowCount()
        }

    }
    Rectangle {
        height: 5
        width: parent.width
        color: "transparent"
    }

    TableView {
        property QtObject renderBuffer: modelData
        property QtObject tableModel: modelData.spreadSheetModel
        id: table
        topMargin: columnsHeader.height
        function getTableWidth() {
            var sum = 0
            for ( var i in columnWidthList) {
                if (i >= tableModel.columnCount())
                    break
                sum += columnWidthList[i]
            }
            return sum + 15
        }
        width: defaultTableWidth
        implicitHeight: tableBackground.height - 40
        clip: true
        property var columnWidthList: [75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75]
        columnWidthProvider: function (column) { return columnWidthList[column]; }
        ScrollBar.horizontal: ScrollBar { 
            orientation: Qt.Horizontal 
            contentItem: Rectangle {
                        implicitHeight: 10
                        radius: width / 4
                        color: activePalette.highlight
                    }
        }
        ScrollBar.vertical: ScrollBar { 
            id: verticalScrollBar 
            contentItem: Rectangle {
                        implicitWidth: 10
                        radius: width / 4
                        color: activePalette.highlight
                    }
        }

        model: modelData.spreadSheetModel
        delegate: DelegateChooser {
            DelegateChoice {
                delegate: DefaultTextField {
                    text: model.display
                    implicitHeight: 30
                    font.pointSize: 8
                    verticalAlignment: Text.AlignVCenter
                    horizontalAlignment: Text.AlignHCenter
                    selectByMouse: false
                    readOnly: true
                    Layout.fillWidth: true
                    implicitWidth: table.columnWidthProvider(column)
                    background: Rectangle {
                        border.width: activeFocus ? 2 : 1
                        color: activePalette.mid
                        border.color: activeFocus ? activePalette.highlight : activePalette.midlight
                    }
                }
            }
        }

        Item {
            id: invisibleItem
            //visible: false
        }

        Label {
            id: label
            parent: invisibleItem
            anchors.right: parent.right
            anchors.verticalCenter: parent.verticalCenter
            font.pointSize: 12
            color: activePalette.text
        }
        //Columns Header
        Row {
            id: columnsHeader
            height: 30
            y: table.contentY
            z: 2
            Repeater {
                id: repeater
                model: modelData.spreadSheetModel.columnNames // table.columns > 0 ? table.columns : 1
                delegate: DropArea {
                    id: dragTarget
                    width: repeaterItem.width
                    height: columnsHeader.height
                    onEntered: {
                        drag.source.caughtId = index
                    }
                    DefaultButton {
                        id: repeaterItem
                        z: 2 // dragArea.drag.active ? 2 : 1
                        width: table.columnWidthProvider(index)
                        height: parent.height
                        text: "<b>"+modelData+"</b>"
                        padding: 10
                        Drag.active: dragArea.drag.active
                        Drag.source: dragArea
                        Drag.hotSpot.x: width / 2
                        Drag.hotSpot.y: height / 2

                        MouseArea {
                            id: dragArea
                            width: parent.width
                            height: parent.height
                            anchors.right: parent.right

                            drag.axis: Drag.XAxis
                            drag.target: parent
                            
                            property point beginDrag
                            property point dropTarget
                            property int caughtId: index
                            property int oldInd: index
                            onPressed: {
                                parent.background.opacity = 0.5
                                dragArea.beginDrag = Qt.point(parent.x, parent.y);
                            }
                            onReleased: {
                                parent.background.opacity = 1
                                // console.log("dragArea.caughtId: " + dragArea.caughtId)
                                if (caughtId != oldInd) {
                                    // reset sorting function
                                    var sort = 0
                                    label.text = ""
                                    label.parent = invisibleItem
                                    table.tableModel.setSort(index, sort)
                                    table.tableModel.swap(oldInd, caughtId)
                                    table.renderBuffer.renderStateChanged()
                                } else {
                                    backAnimX.from = parent.x;
                                    backAnimX.to = beginDrag.x;
                                    backAnim.start()
                                }
                            }
                            function singleClick() {
                                var sort = table.tableModel.getSort(index)
                                switch(sort) {
                                    case 0:
                                        sort = 1 // ascending order
                                        label.text = "∧"
                                        label.parent = repeaterItem
                                        break;
                                    case 1:
                                        sort = -1 // descending order
                                        label.text = "∨"
                                        label.parent = repeaterItem
                                        break;
                                    case -1:
                                        sort = 0
                                        label.text = ""
                                        label.parent = repeaterItem
                                        break;
                                    default:
                                        break;
                                }
                                table.tableModel.setSort(index, sort)
                                table.renderBuffer.renderStateChanged()
                            }
                            Timer {
                                id: timer
                                interval: 100
                                onTriggered: parent.singleClick()
                            }
                            onClicked: {
                                // console.log("timer.restart()")
                                timer.restart()
                            }
                            onDoubleClicked: {
                                // console.log("timer.stop()")
                                timer.stop() // stop single click handler, than trigger double click handler
                                // console.log("repeaterItem.text.length:" + repeaterItem.text.length)
                                var tmp = table.columnWidthList[index]
                                table.columnWidthList[index] = repeaterItem.text.length * 7
                                repeaterItem.width = table.columnWidthList[index]
                                table.contentWidth = table.contentWidth + table.columnWidthList[index] - tmp
                                table.forceLayout()
                            }
                            

                        } // dragArea
                        ParallelAnimation {
                            id: backAnim
                            SpringAnimation { id: backAnimX; target: repeaterItem; property: "x"; duration: 300; spring: 2; damping: 0.2 }
                        }


                        states: [
                            State {
                                when: dragTarget.containsDrag
                                PropertyChanges {
                                    target: repeaterItem
                                    background.color: "grey"
                                }
                            }
                        ]
                        Rectangle {
                            id: resizeHandle
                            color: activePalette.window
                            height: parent.height
                            width: 4
                            anchors.horizontalCenter: parent.right
                            anchors.verticalCenter: parent.verticalCenter
                            MouseArea {
                                id: mouseHandle
                                anchors.fill: parent
                                drag{ target: parent; axis: Drag.XAxis }
                                hoverEnabled: true
                                cursorShape: Qt.SizeHorCursor
                                onMouseXChanged: {
                                    if (drag.active) {
                                        var newWidth = repeaterItem.width + mouseX
                                        if (newWidth >= 30) {
                                            repeaterItem.width = newWidth
                                            table.columnWidthList[index] = newWidth
                                            table.contentWidth = table.contentWidth + mouseX
                                            table.forceLayout()
                                        }
                                    }
                                }
                            }
                        }

                    }
                
                }
            }
            
        }
    }
}
}

