#  Copyright 2017 Carlos Pascual-Izarra <cpascual@users.sourceforge.net>
#
#  This file is part of PeakEvo.
#
#  PeakEvo 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.
#
#  PeakEvo 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 Foobar.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys

from qtpy import QtGui, QtWidgets, uic


class FilesTable(QtWidgets.QWidget):
    """A table of selected files and corresponding x values"""

    X, XPEAK, YPEAK, PRESSURE, FNAME = range(5)

    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent=parent)

        # load ui
        uipath = os.path.join(os.path.dirname(__file__), "filetable.ui")
        uic.loadUi(uipath, self)

        # set icons:
        self.addBT.setIcon(QtGui.QIcon("icons:list-add.svg"))
        self.downBT.setIcon(QtGui.QIcon("icons:go-down.svg"))
        self.upBT.setIcon(QtGui.QIcon("icons:go-up.svg"))
        self.removeBT.setIcon(QtGui.QIcon("icons:edit-table-delete-row.svg"))
        self.exportBT.setIcon(QtGui.QIcon("icons:document-export.svg"))
        self.newBT.setIcon(QtGui.QIcon("icons:list-remove.svg"))

        self.addBT.clicked.connect(self.addFiles)
        self.downBT.clicked.connect(self.moveDown)
        self.upBT.clicked.connect(self.moveUp)
        self.removeBT.clicked.connect(self.removeSelectedRows)
        self.exportBT.clicked.connect(self.exportSelectedRows)
        self.newBT.clicked.connect(self.clear)

        # TODO: process file on load using current spectrum ROI
        # TODO: connect row selection to display of current spectrum

    def addFiles(self, checked=None, files=None):
        if files is None:
            dir = self.parent().acqSettings.outDirLE.text()
            files, _ = QtWidgets.QFileDialog.getOpenFileNames(
                self, "Add files", dir, "numpy (*.npz);;Text files (*.txt)"
            )
        for name in files:
            self.appendRow(name=name)

    def appendRow(self, x="", peak="", ypeak="", pressure="", name=""):
        t = self.table
        row = t.rowCount()
        t.setRowCount(row + 1)
        t.setItem(row, self.X, QtWidgets.QTableWidgetItem(str(x)))
        t.setItem(row, self.XPEAK, QtWidgets.QTableWidgetItem(str(peak)))
        t.setItem(row, self.YPEAK, QtWidgets.QTableWidgetItem(str(ypeak)))
        t.setItem(row, self.PRESSURE, QtWidgets.QTableWidgetItem(str(pressure)))
        t.setItem(row, self.FNAME, QtWidgets.QTableWidgetItem(str(name)))

    def swapRows(self, row1, row2):
        for i in range(self.table.columnCount()):
            item1 = self.table.takeItem(row1, i)
            item2 = self.table.takeItem(row2, i)
            self.table.setItem(row1, i, item2)
            self.table.setItem(row2, i, item1)

    def removeSelectedRows(self):
        # remove starting from the larger row
        revrows = sorted(self.selectedRows(), reverse=True)
        for row in revrows:
            self.table.removeRow(row)

    def moveUp(self):
        row = self.table.currentRow()
        if row <= 0:
            return
        self.swapRows(row, row - 1)
        self.table.setCurrentCell(row - 1, 1)

    def moveDown(self):
        row = self.table.currentRow()
        if row >= self.table.rowCount() - 1:
            return
        self.swapRows(row, row + 1)
        self.table.setCurrentCell(row + 1, 1)

    def selectedRows(self):
        ret = []
        for r in self.table.selectedRanges():
            ret.extend(range(r.topRow(), r.bottomRow() + 1))
        return ret

    def selectRow(self, row=-1, clear=True):
        if row < 0:
            row += self.table.rowCount()
        if clear:
            self.table.clearSelection()
        self.table.setCurrentCell(row, 0)

    def exportSelectedRows(self):
        ncols = self.table.columnCount()
        rows = self.selectedRows()
        if not rows:
            return

        _fname, _ = QtWidgets.QFileDialog.getSaveFileName(
            parent=self,
            caption="Export selected rows",
            filter=".dat files(*.dat);;All files(*)",
        )

        if not _fname:
            return

        with open(_fname, "w") as f:
            hdr = [self.table.horizontalHeaderItem(col).text() for col in range(ncols)]
            f.write("\t".join(hdr))
            for row in rows:
                items = [
                    self.table.item(row, col).text() or "---" for col in range(ncols)
                ]
                f.write("\n")
                f.write("\t".join(items))

    def clear(self):
        self.table.clearContents()
        self.table.setRowCount(0)


if __name__ == "__main__":
    import glob

    app = QtWidgets.QApplication(sys.argv)

    w = FilesTable()
    w.show()

    pattern = os.path.join(os.path.dirname(__file__), "..", "peakevo_out", "*.npz")

    w.addFiles(files=glob.glob(pattern)[:5])

    sys.exit(app.exec_())
