# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'C:\MBFDev\CustomApplicationWork\SPARC\verify XML data\gui_output.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from os import path
import xml.etree.ElementTree as ET
from . tacchkdlg import maketacchkdlg

class Ui_mdgForm(object):
    def __init__(self):
        self.fnametopath = dict()
        self.fnametotree = dict()
        self.justsaved = False
        self.cols = [
            "Filename",
            "Subject: Species",
            "Subject: ID",
            "Subject: Sex",
            "Subject: Age",
            "Atlas: Organ",
            "Atlas: Label",
            "Atlas: Root ID"
        ]
        
    def setupUi(self, mdgForm):
        mdgForm.setObjectName("mdgForm")
        mdgForm.resize(1200, 300)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(mdgForm)
        self.horizontalLayout_2.setContentsMargins(5, 5, 5, 5)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.vLayout = QtWidgets.QVBoxLayout()
        self.vLayout.setObjectName("vLayout")
        self.btnAdd = QtWidgets.QPushButton(mdgForm)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.btnAdd.sizePolicy().hasHeightForWidth())
        self.btnAdd.setSizePolicy(sizePolicy)
        self.btnAdd.setMaximumSize(QtCore.QSize(300, 16777215))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.btnAdd.setFont(font)
        self.btnAdd.setFocusPolicy(QtCore.Qt.NoFocus)
        self.btnAdd.setObjectName("btnAdd")
        self.vLayout.addWidget(self.btnAdd)
        self.btnRemove = QtWidgets.QPushButton(mdgForm)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.btnRemove.sizePolicy().hasHeightForWidth())
        self.btnRemove.setSizePolicy(sizePolicy)
        self.btnRemove.setMaximumSize(QtCore.QSize(300, 16777215))
        self.btnRemove.setFont(font)
        self.btnRemove.setFocusPolicy(QtCore.Qt.NoFocus)
        self.btnRemove.setObjectName("btnRemove")
        self.vLayout.addWidget(self.btnRemove)
        self.hLine = QtWidgets.QFrame(mdgForm)
        self.hLine.setFrameShape(QtWidgets.QFrame.HLine)
        self.hLine.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.hLine.setObjectName("hLine")
        self.vLayout.addWidget(self.hLine)
        self.btnSave = QtWidgets.QPushButton(mdgForm)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.btnSave.setFont(font)
        self.btnSave.setObjectName("btnSave")
        self.vLayout.addWidget(self.btnSave)
        self.horizontalLayout_2.addLayout(self.vLayout)
        self.vLine = QtWidgets.QFrame(mdgForm)
        self.vLine.setFrameShape(QtWidgets.QFrame.VLine)
        self.vLine.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.vLine.setObjectName("vLine")
        self.horizontalLayout_2.addWidget(self.vLine)
        self.tblFiles = QtWidgets.QTableWidget(mdgForm)
        self.tblFiles.setFocusPolicy(QtCore.Qt.NoFocus)
        self.tblFiles.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
        self.tblFiles.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectItems)
        self.tblFiles.setColumnCount(8)
        self.tblFiles.setObjectName("tblFiles")
        self.tblFiles.setRowCount(0)
        self.tblFiles.setHorizontalHeaderLabels(self.cols)
        self.horizontalLayout_2.addWidget(self.tblFiles)
        self.horizontalLayout_2.setStretch(2, 1)

        self.retranslateUi(mdgForm)
        QtCore.QMetaObject.connectSlotsByName(mdgForm)

        self.makeconnections()

    def retranslateUi(self, mdgForm):
        _translate = QtCore.QCoreApplication.translate
        mdgForm.setWindowTitle(_translate("mdgForm", "Form"))
        self.btnAdd.setText(_translate("mdgForm", "Add Files"))
        self.btnRemove.setText(_translate("mdgForm", "Remove Files"))
        self.btnSave.setText(_translate("mdgForm", "Save Changes"))

    def makeconnections(self):
        self.btnAdd.released.connect(self.on_btnAdd_clicked)
        self.btnRemove.released.connect(self.on_btnRemove_clicked)
        self.btnSave.released.connect(self.on_btnSave_clicked)
        self.tblFiles.itemSelectionChanged.connect(self.on_tblFiles_item_changed)

    def checkXML(self, root):
        #print(root)
        itfound = False
        rdict = dict()
        for colind in range(1, len(self.cols)):
            rdict[self.cols[colind]] = ""
        for item in root:
            #print("  " + str(item))
            if item.tag == "sparcdata":
                itfound = True
                sdroot = item
                sdfound = False
                atfound = False
                for child in sdroot:
                    #print("    " + str(child))
                    if child.tag == "subject":
                        sdfound = True
                        keyset = set(child.attrib.keys())
                        if "species" in keyset:
                            rdict[self.cols[1]] = child.attrib["species"]
                        if "subjectid" in keyset:
                            rdict[self.cols[2]] = child.attrib["subjectid"]
                        if "sex" in keyset:
                            rdict[self.cols[3]] = child.attrib["sex"]
                        if "age" in keyset:
                            rdict[self.cols[4]] = child.attrib["age"]
                    elif child.tag == "atlas":
                        atfound = True
                        keyset = child.attrib.keys()
                        if "organ" in keyset:
                            rdict[self.cols[5]] = child.attrib["organ"]
                        if "label" in keyset:
                            rdict[self.cols[6]] = child.attrib["label"]
                        if "rootid" in keyset:
                            rdict[self.cols[7]] = child.attrib["rootid"]
                    if sdfound and atfound:
                        break
        return rdict

    def rebuildtable(self):
        if self.justsaved:
            self.tblFiles.clearContents()
            self.tblFiles.setRowCount(0)
            self.addfromlist(list(self.fnametopath.values()))
            self.justsaved = False

    def addfromlist(self, flist):
        for fpath in flist:
            #print("  got fpath")
            tree = ET.parse(fpath)
            #print("  got tree")
            root = tree.getroot()
            #print("  got root")
            rowinfo = self.checkXML(root)
            #print("  checked XML")
            fname = path.basename(fpath)
            #print("  got fname: " + fname)
            self.fnametopath[fname] = fpath
            self.fnametotree[fname] = tree
            #print("  added dict data")
            self.tblFiles.insertRow(self.tblFiles.rowCount())
            #print("  inserted row")
            newitem = QtWidgets.QTableWidgetItem(fname)
            #print("  made new item")
            newitem.setFlags(newitem.flags() ^ Qt.ItemIsEditable)
            #print("  set item flags")
            filled = not "" in rowinfo.values()
            if filled:
                newitem.setBackground(Qt.green)
            self.tblFiles.setItem(self.tblFiles.rowCount()-1, 0, newitem)
            #print("  set item")
            for colind in range(1,len(self.cols)):
                #print(rowinfo)
                #print()
                #print(colind)
                #print()
                #print(self.cols[colind])
                #print("    " + str(colind))
                text = rowinfo[self.cols[colind]]
                #print("    got text")
                newitem = QtWidgets.QTableWidgetItem(text)
                #print("    made new item")
                if filled:
                    newitem.setBackground(Qt.green)
                elif not text:
                    if colind != 2:
                        newitem.setBackground(Qt.red)
                    else:
                        newitem.setBackground(Qt.yellow)
                self.tblFiles.setItem(self.tblFiles.rowCount()-1, colind, newitem)
                #print("    set new item")
        self.tblFiles.resizeColumnsToContents()
        #print("table resized")

    def on_tblFiles_item_changed(self):
        for rowind in range(self.tblFiles.rowCount()):
            rowtxts = list()
            for colind in range(self.tblFiles.columnCount()):
                item = self.tblFiles.item(rowind, colind)
                rowtxts.append(item.text())
            if not "" in rowtxts:
                for colind in range(self.tblFiles.columnCount()):
                    self.tblFiles.item(rowind, colind).setBackground(Qt.green)
            else:
                for colind in range(self.tblFiles.columnCount()):
                    text = self.tblFiles.item(rowind, colind).text()
                    if text:
                        self.tblFiles.item(rowind, colind).setBackground(Qt.white)
                    elif colind != 2:
                        self.tblFiles.item(rowind, colind).setBackground(Qt.red)
                    else:
                        self.tblFiles.item(rowind, colind).setBackground(Qt.yellow)

    def on_btnAdd_clicked(self):
        #print("clicked")
        self.rebuildtable()
        #print("rebuilt")
        flist, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Add XML Files", directory="C:\\", filter="XML Files (*.xml)")
        #print("got flist")
        fset = set(flist)
        #print("got set")
        fset = fset - set(self.fnametopath.values())
        #print("subtracted set")
        flist = list(fset)
        #print("got list")
        self.addfromlist(flist)
        #print("added")
            
    def on_btnRemove_clicked(self):
        self.rebuildtable()
        rlist = list()
        sranges = self.tblFiles.selectedRanges()
        #print(sranges)
        for srange in sranges:
            start = srange.topRow()
            end = srange.bottomRow()
            for row in range(start, end + 1):
                rlist.append(row)
        rlist.sort(reverse=True)
        #print(rlist)
        for row in rlist:
            #print("  " + str(row))
            fitem = self.tblFiles.item(row, 0)
            fname = fitem.text()
            #print("  fname:" + fname)
            self.tblFiles.removeRow(row)
            #print("  removed")
            del self.fnametopath[fname]
            del self.fnametotree[fname]
            #print("  deleted")
        self.tblFiles.resizeColumnsToContents()

    def on_btnSave_clicked(self):
        #print("saving")
        for rowind in range(self.tblFiles.rowCount()):
            fitem = self.tblFiles.item(rowind,0)
            #print(fitem.background().color())
            fname = fitem.text()
            #print("  " + fname)
            #print(fname)
            tree = self.fnametotree[fname]
            #print("  got tree")
            #print(tree)
            root = tree.getroot()
            #print("  got root")
            #print(root)
            sparcdata = root.find("sparcdata")
            #print("  got sparcdata")
            subject = None
            atlas = None
            if sparcdata is None:
                #print("    sparcdata is None")
                sparcdata = ET.SubElement(root, "sparcdata")
                subject = ET.SubElement(sparcdata, "subject")
                subject.set("species","")
                subject.set("subjectid","")
                subject.set("sex","")
                subject.set("age","")
                atlas = ET.SubElement(sparcdata, "atlas")
                atlas.set("organ","")
                atlas.set("label","")
                atlas.set("rootid","")
            else:
                #print("    sparcdata exists")
                subject = sparcdata.find("subject")
                if subject is None:
                    #print("    subject is None")
                    subject = ET.SubElement(sparcdata, "subject")
                    subject.set("species","")
                    subject.set("subjectid","")
                    subject.set("sex","")
                    subject.set("age","")
                #else:
                    #print("    subject exists")
                atlas = sparcdata.find("atlas")
                if atlas is None:
                    #print("  atlas is None")
                    atlas = ET.SubElement(sparcdata, "atlas")
                    atlas.set("organ","")
                    atlas.set("label","")
                    atlas.set("rootid","")
                #else:
                    #print("    atlas exists")
            #print("  got all data places")
            for colind in range(1,len(self.cols)):
                ditem = self.tblFiles.item(rowind,colind)
                #print(ditem.background().color())
                reptext = ditem.text()
                #if len(reptext) < 1:
                    #print("    [reptext empty]")
                #else:
                    #print("    " + reptext)
                if colind == 1:
                    subject.attrib["species"] = reptext
                elif colind == 2:
                    subject.attrib["subjectid"] = reptext
                elif colind == 3:
                    subject.attrib["sex"] = reptext
                elif colind == 4:
                    subject.attrib["age"] = reptext
                if colind == 5:
                    atlas.attrib["organ"] = reptext
                elif colind == 6:
                    atlas.attrib["label"] = reptext
                elif colind == 7:
                    atlas.attrib["rootid"] = reptext
            #print("  finished looping")
            fpath = self.fnametopath[fname]
            #print("  fpath: " + fpath)
            tree.write(fpath)
            #print("  tree written")
            for colind in range(self.tblFiles.columnCount()):
                ritem = self.tblFiles.item(rowind,colind)
                ritem.setBackground(Qt.cyan)
        self.tblFiles.clearSelection()
        self.justsaved = True
        #print("making msgbox")
        tacmsgbox = maketacchkdlg(list(self.fnametopath.values()))
        #print("showing msgbox")
        _ = tacmsgbox.exec_()
        #print("msgbox closed")
