from qgis.PyQt.QtWidgets import QDialog, QGridLayout, QTreeWidget, QTreeWidgetItem


class LayerIdentification(QDialog):
    # 이 클래스는 Map tab에서 레이어 우클릭으로 선택된 객체에 대한 속성정보를 표시하는 작업을 함.
    def __init__(self, layers, parent=None):
        super(LayerIdentification, self).__init__(parent)

        self.layers = layers

        self.initUI()
        self.showFeatures()
        self.show()

    def initUI(self):
        self.trw_list = QTreeWidget()
        self.trw_list.setColumnCount(2)
        self.trw_list.setHeaderLabels(["객체", "값"])
        self.trw_list.setColumnWidth(1, 100)
        #         self.trw_list.setHeaderHidden(True)

        self.layout = QGridLayout()
        self.layout.addWidget(self.trw_list)

        self.setLayout(self.layout)
        self.setGeometry(200, 200, 400, 600)

    def showFeatures(self):
        for i, layer in enumerate(self.layers):
            layerName = layer.name()
            feature = layer.getSelectedFeatures()
            flag = False

            firstItem = QTreeWidgetItem([layerName, ""])
            for j, f in enumerate(feature):
                flag = True
                secondItem = QTreeWidgetItem([f"속성 {j}", ""])
                for field in f.fields().names():
                    thirdItem = QTreeWidgetItem([field, str(f[field])])
                    secondItem.addChild(thirdItem)
                firstItem.addChild(secondItem)

            if flag:
                self.trw_list.addTopLevelItem(firstItem)
