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

Rectangle {
    id: tableBackground
    color: activePalette.dark
    width: table.getTableWidth() + 15
    implicitHeight: scene3d.height
    onVisibleChanged: {
        implicitWidth = table.getTableWidth() + 15
    }

    property var checkBoxIndicatorSize: 18
    property var currentSelectedRow: 0
    property var start_row: 0
    property var rowNum: {
        return modelData.columnModel.rowCount()
    }
    property var data_list: [
        {
            text: "default", 
            num: rowNum, 
            flags: [ true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                    true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, 
                ]
        }
        ]
    
    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)
            }
        }
    }
Column {
    id: root
    x: 10
    Layout.alignment : Qt.AlignTop
    Layout.fillWidth: true
    Layout.minimumWidth: 320
    Layout.preferredWidth: 320
    Layout.maximumWidth: 4000

    Action {
        shortcut: "Ctrl+Up"
        onTriggered: {
            for(var i = 0; i < rowNum; i++) {
                modelData.setColumnDisplayedFlag(i, false, false)
            }
            var t = currentSelectedRow - 1
            if (t < 0) t = rowNum - 1
            modelData.setColumnDisplayedFlag(t, true)
            currentSelectedRow = t
        }
    }
    Action {
        shortcut: "Ctrl+Down"
        onTriggered: {
            for(var i = 0; i < rowNum; i++) {
                modelData.setColumnDisplayedFlag(i, false, false)
            }
            var t = currentSelectedRow + 1
            if (t >= rowNum) t = 0
            modelData.setColumnDisplayedFlag(t, true)
            currentSelectedRow = t
        }
    }
    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
                checked: true
                implicitHeight: parent.height
                indicator.height : checkBoxIndicatorSize
                indicator.width : checkBoxIndicatorSize
                nextCheckState: function() {
                    var select_list = modelData.columnModel.selectRows()
                    if (checkState == Qt.Unchecked) {
                        for(var i = 0; i < rowNum; i++) {
                            if (select_list[i])
                                modelData.setColumnDisplayedFlag(i, true, false)
                        }
                        for(var i = 0; i < rowNum; i++) {
                            if (select_list[i]) {
                                modelData.setColumnDisplayedFlag(i, true)
                                break;
                            }
                        }
                        return Qt.Checked
                    }
                    else {
                        for(var i = 0; i < rowNum; i++) {
                            if (select_list[i])
                                modelData.setColumnDisplayedFlag(i, false, false)
                        }
                        for(var i = 0; i < rowNum; i++) {
                            if (select_list[i]) {
                                modelData.setColumnDisplayedFlag(i, false)
                                break;
                            }
                        }
                        return Qt.Unchecked
                    }
                }            
                ToolTip {
                    visible: parent.hovered
                    delay: 500
                    text: qsTr("Toggle Selected Columns")
                }
            }
        }
        function saveColumnsGroupsList() {
            var json_text =  JSON.stringify(data_list);
            console.log(json_text)
            var xhr = new XMLHttpRequest();
            var file_path = config.string2url(config.getDocuments())+"/PandarViewDataFiles/columns_groups.json"
            console.log(file_path)
            xhr.open("PUT", file_path);
            xhr.send(json_text);
        }
        function loadColumnsGroupsList() {
            var xhr = new XMLHttpRequest();
            var file_path = config.string2url(config.getDocuments())+"/PandarViewDataFiles/columns_groups.json"
            console.log(file_path)
            xhr.open("GET", file_path);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == XMLHttpRequest.DONE) {
                    var response = xhr.responseText;
                    // console.log("response:" + response)
                    if (response && data_list) {
                        // use file contents as required
                        data_list = JSON.parse(response);
                        console.log(data_list)
                        cbItems.clear();
                        for(var i in data_list) {
                            console.log(data_list[i])
                            cbItems.append( data_list[i] )
                        }
                    }
                }
            };
            xhr.send();
        }
        DefaultComboBox {
            id: groupListComboBox
            focusPolicy: Qt.NoFocus
            implicitWidth: 120
            implicitHeight: parent.height
            model: ListModel {
                id: cbItems
                ListElement { text: "default"; }
            }
            onCurrentIndexChanged: {
                // console.log(currentIndex, data_list[currentIndex])
                if (currentIndex >= 0 && currentIndex < data_list.length) {
                    var flags = data_list[currentIndex].flags
                    for(var i = 0; i < rowNum; i++) {
                        modelData.setColumnDisplayedFlag(i, flags[i], false)
                    }
                    modelData.setColumnDisplayedFlag(0, flags[0])
                }
            }
            Component.onCompleted: {
                var flags = []
                for(var i = 0; i < rowNum; i++) {
                    var flag = modelData.columnModel.data(modelData.columnModel.index(i, 0))
                    flags.push(flag)
                }
                var item = {
                    text: modelName.text, 
                    num: rowNum, 
                    flags: flags
                }
                data_list = []
                data_list.push(item)
                toolBar.loadColumnsGroupsList()
            }
            ToolTip {
                visible: parent.hovered
                delay: 500
                text: qsTr("Select group of columns")
            }
        }

        Window {
            id: addWindow
            title : "Add Columns Bundle"
            width: addContent.width + 20
            height: addContent.height
            color: activePalette.window
            flags:  Qt.Dialog 
                    | Qt.WindowSystemMenuHint | Qt.WindowTitleHint 
                    | Qt.WindowCloseButtonHint | Qt.WindowOkButtonHint 
                    | Qt.FrameWindowHint

            visible: true
            modality: Qt.NonModal 
            ColumnLayout {
                id: addContent
                x: 10
                spacing: 5
                Rectangle {
                    height: 5
                }
                Label {
                    text: "Columns Bundle Name"
                    color: activePalette.text
                    
                }
                Rectangle {
                    width: 200
                    height: 32
                    color: activePalette.dark
                    TextInput {
                        id: modelName
                        text: "test case"
                        width: parent.width
                        height: parent.height
                        selectByMouse: true
                        onActiveFocusChanged: {
                            // When we first gain focus, select everything for clearing.
                            if (activeFocus) {
                                selectAll()
                            }
                        }
                        onEditingFinished: {
                            control.focus = false
                        }
                        
                        color: activePalette.text
                        selectionColor: activePalette.highlight
                        selectedTextColor: activePalette.highlightedText
                        horizontalAlignment: Qt.AlignHCenter
                        verticalAlignment: Qt.AlignVCenter
                    }
                }
                RowLayout {
                    Rectangle {
                        width: 60
                        height: 40
                        color: activePalette.window    
                    }
                    DefaultButton {
                        text: "Cancel"
                        
                        implicitWidth: 70
                        implicitHeight: 32
                        onClicked: addWindow.close()
                    }
                    DefaultButton {
                        text: "Ok"
                        
                        implicitWidth: 70
                        implicitHeight: 32
                        onClicked: {
                            var flags = []
                            for(var i = 0; i < rowNum; i++) {
                                var flag = modelData.columnModel.data(modelData.columnModel.index(i, 0))
                                // console.log(flag)
                                flags.push(flag)
                            }
                            var item = {
                                text: modelName.text, 
                                num: rowNum, 
                                flags: flags
                            }
                            // console.log(item.text + " " + item.num + " " + item.flags)
                            data_list.push(item)
                            // console.log(data_list)
                            cbItems.append(item)

                            toolBar.saveColumnsGroupsList()
                            addWindow.close()
                        }
                    }
                }
                Rectangle {
                    height: 5
                }
            }
        }
        DefaultToolButton {
            focusPolicy: Qt.NoFocus
            implicitWidth: 30
            implicitHeight: 30
            icon.source: "file:png/add.png"

            onClicked: {
                addWindow.show()
            }
            ToolTip {
                visible: parent.hovered
                delay: 500
                text: qsTr("Save the current column selection")
            }
        }
        DefaultToolButton {
            focusPolicy: Qt.NoFocus
            implicitWidth: 30
            implicitHeight: 30
            icon.source: "file:png/delete.png"

            onClicked: {
                var target = groupListComboBox.currentIndex
                var tmp_list = []
                cbItems.clear();
                for(var i in data_list) {
                    if ( target != i) {
                        console.log(data_list[i])
                        cbItems.append( data_list[i] )
                        tmp_list.push( data_list[i] )
                    }
                }
                data_list = tmp_list
                toolBar.saveColumnsGroupsList()
            }
            ToolTip {
                visible: parent.hovered
                delay: 500
                text: qsTr("Delete the current column selection")
            }
        }
    }
    Rectangle {
        height: 5
        width: parent.width
        color: "transparent"
    }

TableView {
    id: table
    topMargin: columnsHeader.implicitHeight
    // width: root.width
    function getTableWidth() {
        var sum = 0
        for ( var i in columnWidthList) {
            sum += columnWidthList[i]
        }
        return sum + 15
    }
    width: getTableWidth()
    implicitHeight: tableBackground.height - 40
    clip: true
    property var defaultRowHeight: 32
    property var headerName: ["", "CS #", "Elevation", "Azimuth"]
    property var columnWidthList : [40, 60, 100, 100]
    columnWidthProvider: function (column) { return columnWidthList[column]; }
    ScrollBar.horizontal: ScrollBar { 
        orientation: Qt.Horizontal
        contentItem: Rectangle {
                    implicitWidth: 10
                    radius: width / 4
                    color: activePalette.highlight
                    } 
    }
    ScrollBar.vertical: ScrollBar { 
        id: verticalScrollBar
        contentItem: Rectangle {
                    implicitWidth: 10
                    radius: width / 4
                    color: activePalette.highlight
                    }
    }
    function setColumnDisplayedFlag(idx, flag) {
        modelData.setColumnDisplayedFlag(idx, flag)
    }
    model: modelData.columnModel
    delegate: DelegateChooser {
        DelegateChoice {
            column: 0
            delegate: DefaultCheckBox {
                focusPolicy: Qt.NoFocus
                checked: model.display
                Layout.fillWidth: true
                implicitWidth: table.columnWidthProvider(column)
                implicitHeight: table.defaultRowHeight
                indicator.height : checkBoxIndicatorSize
                indicator.width : checkBoxIndicatorSize
                background: Rectangle {
                    border.width: 1
                    color: model.background ? activePalette.highlight : activePalette.mid
                    border.color: activePalette.midlight
                }
                onToggled: function() {
                    model.display = checked
                    if (checkState == Qt.Checked) {
                        table.setColumnDisplayedFlag(row, true)
                        currentSelectedRow = row
                    } else {
                        table.setColumnDisplayedFlag(row, false)
                    }
                }
            }

        }
        DelegateChoice {
            column: 1
            delegate: DefaultTextField {
                text: model.display
                verticalAlignment: Text.AlignVCenter
                horizontalAlignment: Text.AlignHCenter
                selectByMouse: false
                readOnly: true
                Layout.fillWidth: true
                implicitWidth: table.columnWidthProvider(column)
                implicitHeight: table.defaultRowHeight
                font.pointSize: 9
                color: model.background? activePalette.highlightedText : activePalette.text
                background: Rectangle {
                    border.width: activeFocus? 2 : 1 
                    color: model.background ? activePalette.highlight : activePalette.mid
                    border.color: activePalette.midlight
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        if (mouse.modifiers & Qt.ShiftModifier) {
                            modelData.columnModel.setSelectRange(start_row, row);
                        }
                        else if (mouse.modifiers & Qt.ControlModifier) {
                            modelData.columnModel.setSelectRange(row);
                        }
                        else {
                            start_row = row
                            modelData.columnModel.setSelectRange(-1, row);
                        }
                    }
                }

            }
        }
        DelegateChoice {
            delegate: DefaultTextField {
                text: model.display.toFixed(3)
                verticalAlignment: Text.AlignVCenter
                horizontalAlignment: Text.AlignHCenter
                selectByMouse: false
                readOnly: true
                Layout.fillWidth: true
                implicitWidth: table.columnWidthProvider(column)
                implicitHeight: table.defaultRowHeight
                font.pointSize: 9
                color: model.background? activePalette.highlightedText : activePalette.text
                background: Rectangle {
                    id: bgRect
                    border.width: activeFocus? 2 : 1 
                    color: model.background ? activePalette.highlight : activePalette.mid
                    border.color: activePalette.midlight
                }
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        if (mouse.modifiers & Qt.ShiftModifier) {
                            modelData.columnModel.setSelectRange(start_row, row);
                        }
                        else if (mouse.modifiers & Qt.ControlModifier) {
                            modelData.columnModel.setSelectRange(row);
                        }
                        else {
                            start_row = row
                            modelData.columnModel.setSelectRange(-1, row);
                        }
                    }
                }
            }
        }
    }
    //Columns Header
    Row {
        id: columnsHeader
        y: table.contentY
        z: 2
        Repeater {
            model: table.headerName
            DefaultButton {
                id: title
                width: table.columnWidthProvider(index)
                height: table.defaultRowHeight
                text: "<b>"+modelData+"</b>"
                font.pointSize: 9
                padding: 10
                Rectangle {
                    id: resizeHandle
                    color: activePalette.window
                    height: parent.height
                    width: 2
                    anchors.right: 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 = title.width + mouseX
                                if (newWidth >= 30) {
                                    title.width = newWidth
                                    table.columnWidthList[index] = newWidth
                                    table.contentWidth = table.contentWidth + mouseX
                                    table.width = table.getTableWidth()
                                    tableBackground.width = table.width + 15
                                    table.forceLayout()
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    DefaultCheckBox {
        focusPolicy: Qt.NoFocus
        y: table.contentY
        anchors.left: columnsHeader.left
        z: 3
        checked: true
        implicitHeight: table.defaultRowHeight
        indicator.height : checkBoxIndicatorSize
        indicator.width : checkBoxIndicatorSize
        nextCheckState: function() {
            if (checkState == Qt.Unchecked) {
                for(var i = 0; i < rowNum; i++) {
                    modelData.setColumnDisplayedFlag(i, true, false)
                }
                modelData.setColumnDisplayedFlag(0, true)
                return Qt.Checked
            }
            else {
                for(var i = 0; i < rowNum; i++) {
                    modelData.setColumnDisplayedFlag(i, false, false)
                }
                modelData.setColumnDisplayedFlag(0, false)
                return Qt.Unchecked
            }
        }            
        ToolTip {
            visible: parent.hovered
            delay: 500
            text: qsTr("Toggle All")
        }
    }

}



}

}