# -*- coding: utf-8 -*-
"""
/***************************************************************************
 FillSinkDialog
                                 A QGIS plugin
 FillSink plug-in
                             -------------------
        begin                : 2017-03-13
        git sha              : $Format:%H$
        copyright            : (C) 2017 by Hermesys
        email                : shpark@hermesys.co.kr
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program 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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
import os
import codecs
import tempfile
from qgis.core import *
from PyQt5 import QtGui, uic
from qgis.PyQt import QtGui, QtWidgets, uic
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from .lib.Util import *
from .lib.File_Class import *
from .lib.xmltodict import *
import xml.etree.ElementTree as ET


FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'LandCover.ui'))

class LandCoverDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self,_xmltodic={},_LandCoverCount=0,_GreenAmptCount=0,_SoilDepthCount=0,_grmDialogFlag=0,parent=None):
        super(LandCoverDialog, self).__init__(parent)
        self.setupUi(self)
        # 프로젝트 XML to dic 자료 받아서 전역 변수 셋팅
        self._xmltodict=_xmltodic
        self._LandCoverCount = _LandCoverCount
        self._GreenAmptCount =_GreenAmptCount
        self._SoilDepthCount = _SoilDepthCount
        self._grmDialogFlag=_grmDialogFlag # Setup / Run GRM 창 실행 중인지 확인
        self.StaticDB = os.path.dirname(os.path.realpath(__file__)) + "\DLL\GRMStaticDB.xml"

        print ("self._grmDialogFlag :: "+str(self._grmDialogFlag))

        # 초기에 각각의 컨트롤 들의 기본값을 셋팅
        self.InitControls()


    # 각각의 컨트롤 들을 초기 값이나 설정을 셋팅
    def InitControls(self):

        self.btnCancel.clicked.connect(self.closeForm)
 
        # 확인버튼을 눌렀을 때
        self.btnOK.clicked.connect(self.OKForm)

        #초기 모든 변수값 셋팅
        self.SetProjectValue()

        #콤보 박스에 레이어 목록 적용 값 셋팅
        self.SetLayerListCombobox()

        #라디오 버튼 셋팅
        self.SetRadio()

        #테이블 헤더 설정
        self.SetTableHeader()

        # 각각의 테이블에 데이터 값 읽어서 넣기
        # 1순위 - 프로젝트 파일 데이터
        # 2순위 - 프로젝트 파일 내에 Vat 파일 경로
        self.SetTableData()
        self.tlbLandCover.cellDoubleClicked.connect(lambda: self.aboutApp("LandCover", self.tlbLandCover.currentRow()))
        self.tblGreenAmpt.cellDoubleClicked.connect(lambda: self.aboutApp("GreenAmpt", self.tblGreenAmpt.currentRow()))
        self.tblSoilDepth.cellDoubleClicked.connect(lambda: self.aboutApp("SoilDepth", self.tblSoilDepth.currentRow()))
   
        # 콤보 박스 변경시 선택된 콤보 박스 레이어 목록으로 Table 셋팅
        self.cmbLandCover.activated.connect(lambda :self.Get_ComboBox_LayerPath(self.cmbLandCover,self.tlbLandCover,self.txtLandCover,"LandCover"))
        self.cmbSoilTexture.activated.connect(lambda :self.Get_ComboBox_LayerPath(self.cmbSoilTexture,self.tblGreenAmpt,self.txtSoilTexture,"GreenAmpt"))
        self.cmbSoilDepth.activated.connect(lambda :self.Get_ComboBox_LayerPath(self.cmbSoilDepth,self.tblSoilDepth,self.txtSoilDepth,"SoilDepth"))

        # Vat 선택 버튼 클릭 이벤트(서택된 파일로 테이블값이 변경 됨)
        self.btnVatLand.clicked.connect(lambda :self.SelectVat("btnVatLand",self.txtLandCover))
        self.btnVatAmpt.clicked.connect(lambda :self.SelectVat("btnVatAmpt",self.txtSoilTexture))
        self.btnVatDepth.clicked.connect(lambda :self.SelectVat("btnVatDepth",self.txtSoilDepth))

    # 사용자가 VAT 파일 바꿀때 테이블 값도 바뀌어서 적용
    def SelectVat(self,button,txtbox):
        try:
            dir = os.path.dirname(txtbox.text())
            filename = QFileDialog.getOpenFileName(self, "select output file ", dir, "*.vat")[0]
            if filename:
                txtbox.setText(filename)
                if button=="btnVatLand":
                    self.SetVATValue(self.txtLandCover.text(), self.tlbLandCover,"LandCover")
                elif button=="btnVatAmpt":
                    self.SetVATValue(self.txtSoilTexture.text(), self.tblGreenAmpt,"GreenAmpt")
                elif button == "btnVatDepth":
                    self.SetVATValue(self.txtSoilDepth.text(), self.tblSoilDepth,"SoilDepth")
        except Exception as e:
            MsError(e)



    def Get_ComboBox_LayerPath(self,combox,table,txt,type):
        try:
            if combox.currentIndex()!=0:
                self.layerPath = GetcomboSelectedLayerPath(combox).lower().replace(".asc", ".vat").replace(".tif", ".vat")

                if ChFile_Exists(self.layerPath):
                    txt.setText(str(self.layerPath))
                    self.SetVATValue(self.layerPath, table, type)
        except Exception as e:
            MsError(e)

    def OKForm(self):

        if self.rbtUseLCLayer.isChecked():
            if self.cmbLandCover.currentIndex()==0:
                MsInfo(" layer is not selected ")
                self.cmbLandCover.setFocus()
                return

            if self.txtLandCover.text() =="":
                MsInfo("The VAT file is not selected.")
                self.txtLandCover.setFocus()
                return

        if self.rbtUseSoilTextureLayer.isChecked():
            if self.cmbSoilTexture.currentIndex() == 0:
                MsInfo(" layer is not selected ")
                self.cmbSoilTexture.setFocus()
                return

            if self.txtSoilTexture.text() == "":
                MsInfo( "The VAT file is not selected.")
                self.txtSoilTexture.setFocus()
                return


        if self.rbtUseSoilDepthLayer.isChecked():
            if self.cmbSoilDepth.currentIndex() == 0:
                MsInfo(" layer is not selected ")
                self.cmbSoilDepth.setFocus()
                return

            if self.txtSoilDepth.text() == "":
                MsInfo("The VAT file is not selected.")
                self.txtSoilDepth.setFocus()
                return


        # 1. 라디오 rbtUseConstLCAtt
        if self.rbtUseConstLCAtt.isChecked():
            if self.Checktxtbox(self.txtCoefficient):
                result=float(self.txtCoefficient.text())
                if not(0.0015<=result and  result<=1.5):
                    MsInfo("{0}\n{1}".format(
                        "[Land cover roughness coefficient] is invalid.",
                        "0.0015<=Land cover roughness coefficient<=1.5"))
                    self.txtCoefficient.setFocus()
                    return
            else :
                MsInfo("{0}\n{1}".format(
                    "[Land cover roughness coefficient] is invalid.",
                    "0.0015<=Land cover roughness coefficient<=1.5"))
                self.txtCoefficient.setFocus()
                return


            if self.Checktxtbox(self.txtImpervious):
                result = float(self.txtImpervious.text())
                if not( 0<= result and result<=1):
                    MsInfo("[Impervious ratio] is invalid. \n0<=Impervious ration<=1")
                    self.txtImpervious.setFocus()
                    return
            else:
                MsInfo("[Impervious ratio] is invalid. \n0<=Impervious ration<=1")
                self.txtImpervious.setFocus()
                return

        # 2. rbtUseConstTextureAtt 선택 시,
        if self.rbtUseConstTextureAtt.isChecked():
            if self.Checktxtbox(self.txtPorosity):
                result=float(self.txtPorosity.text())
                if not( 0<= result and result <=1 ):
                    MsInfo("[Porosity] is invalid. \n0<=Porosity<=1")
                    self.txtPorosity.setFocus()
                    return
            else:
                MsInfo("[Porosity] is invalid. \n0<=Porosity<=1")
                self.txtPorosity.setFocus()
                return

            if self.Checktxtbox(self.txtEffective_porosity):
                result= float(self.txtEffective_porosity.text())
                if not(0<= result and result<=1):
                    MsInfo('[Effective poropsity] is invalid. \n0<=Effective porosity<=1')
                    self.txtEffective_porosity.setFocus()
                    return
            else:
                MsInfo('[Effective poropsity] is invalid. \n0<=Effective porosity<=1')
                self.txtEffective_porosity.setFocus()
                return

            if self.Checktxtbox(self.txtSuction_head):
                result = float(self.txtSuction_head.text())
                if not(0<= result and result <=9999):
                    MsInfo('[Wetting front suction head] is invalid. \n0<=Wetting front suction head<=9999')
                    self.txtSuction_head.setFocus()
                    return
            else:
                MsInfo('[Wetting front suction head] is invalid. \n0<=Wetting front suction head<=9999')
                self.txtSuction_head.setFocus()
                return

            if self.Checktxtbox(self.txtConductiovity):
                result = float(self.txtConductiovity.text())
                if not(0<= result and result <=1):
                    MsInfo('[Hydraulic conductivity] is invalid. \n0<=Hydraulic conductivity<=1')
                    self.txtConductiovity.setFocus()
                    return
            else:
                MsInfo( '[Hydraulic conductivity] is invalid. \n0<=Hydraulic conductivity<=1')
                self.txtConductiovity.setFocus()
                return

        # 3.rbtUseConstDepth 체크
        if self.rbtUseConstDepth.isChecked():
            if self.Checktxtbox(self.txtSoil_depth):
                result = float(self.txtSoil_depth.text())
                if not(0<= result and result <=9999):
                    MsInfo( "[Soil Depth] is invalid.\n0<=Soil Depth<=9999")
                    self.txtSoil_depth.setFocus()
                    return
            else:
                MsInfo( "[Soil Depth] is invalid.\n0<=Soil Depth<=9999")
                self.txtSoil_depth.setFocus()
                return

        # GMP 파일에 Lanccover,depth.. xml 생성
        self.DataSave()
        # _util.MessageboxShowInfo("Land cover / soil", "Land covers and soil attributes setup are completed.")

        quit_msg = " Land covers and soil attributes setup are completed.   "
        reply = QMessageBox.information(self, 'Land cover / soil', quit_msg, QMessageBox.Ok)
        if reply == QMessageBox.Ok:
            self.close()

    # QlineEdit 값 체크
    def Checktxtbox(self, textbox):
        if textbox.text() != "" and self.isFloat(textbox.text()):
            return True
        else:
            return False

 # Vat 파일에서 읽어 와서 테이블에 값셋팅 하기
    def SetVATValue(self,path,table,type):
        try:
            if path != "":
                temOutput = tempfile.mktemp() + ".txt"
                #fileObj = codecs.open( path, "r", "utf-8" )
                #lines = fileObj.readlines()
                try:
                    with open(path, 'r', encoding='cp949') as f:
                        lines  = f.readlines()
                except Exception as e:
                    with open(path, 'r', encoding='utf-8') as f:
                        lines  = f.readlines()

            # 테이블 초기화
            table.clear()
            if type == "LandCover":
                table.setColumnCount(5)
                table.setHorizontalHeaderLabels(['GridValue', 'UserLandCover', 'GRMCode','RoughnessCoefficient','ImperviousRatio'])

            elif type == "GreenAmpt":
                table.setColumnCount(7)
                table.setHorizontalHeaderLabels(['GridValue', 'USERSoil', 'GRMCode', 'Porosity', 'EffectivePorosity','WFSoilSuctionHead', 'HydraulicConductivity'])
            elif type == "SoilDepth":
                table.setColumnCount(4)
                table.setHorizontalHeaderLabels(['GridValue', 'UserDepthClass', 'GRMCode', 'SoilDepth'])
            table.setRowCount(int(len(lines)))


            # Table에 데이터 값 대입
            for i in range(0, len(lines)):
                if lines[i] is not None and lines[i]!="":
                    splitsdata = lines[i].split(",")
                    #item1 = QTableWidgetItem(splitsdata[0])
                    item1 = QTableWidgetItem(splitsdata[0])
                    item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    table.setItem(i, 0, QTableWidgetItem(item1))
                    item2 = QTableWidgetItem(splitsdata[1])
                    item2.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    table.setItem(i, 1, QTableWidgetItem(item2))

                    txtvalue=splitsdata[1]
                    if txtvalue.upper()=="USER":
                        user = True
                    else:
                        user = False
                    self.SetMainTableValue(splitsdata[1].strip(),table,(i),type,user)
        except Exception as es:
           MsError(es)

    # 메인창 Land cover tablewidget 테이블에 데이터 셋팅 (3~ 이후 컬럼의 데이터 값을 StaticDB 셋팅)
    def SetMainTableValue(self, value, widget, row, type,user):


        doc = ET.parse(self.StaticDB)
        root = doc.getroot()
        if type == "LandCover":
            for element in root.findall("{http://tempuri.org/DataSet1.xsd}LandCoverParameter"):
                if user:
                    item1 = QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
                    item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    widget.setItem(row, 2, QTableWidgetItem("USER"))
                    widget.setItem(row, 3, QTableWidgetItem(""))
                    widget.setItem(row, 4, QTableWidgetItem(""))
                    break                    
                else:
                    if element.findtext("{http://tempuri.org/DataSet1.xsd}LandCoverK") == value :
                        item1 = QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
                        item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                        widget.setItem(row, 2, QTableWidgetItem(item1))
                        widget.setItem(row, 3, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}RoughnessCoefficient")))
                        widget.setItem(row, 4, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}ImperviousRatio")))
                        break

                    #2019-02-21 박: 다른 조건에서도 데이터 들어오게 처리
                    elif element.findtext("{http://tempuri.org/DataSet1.xsd}LandCoverE") == value :
                        item1 = QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
                        item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                        widget.setItem(row, 2, QTableWidgetItem(item1))
                        widget.setItem(row, 3, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}RoughnessCoefficient")))
                        widget.setItem(row, 4, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}ImperviousRatio")))
                        break

                    #2019-02-21 박: 다른 조건에서도 데이터 들어오게 처리
                    elif element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode") == value :
                        item1 = QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
                        item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                        widget.setItem(row, 2, QTableWidgetItem(item1))
                        widget.setItem(row, 3, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}RoughnessCoefficient")))
                        widget.setItem(row, 4, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}ImperviousRatio")))
                        break
                        
        elif type == "GreenAmpt":
            for element in root.findall("{http://tempuri.org/DataSet1.xsd}GreenAmptSoilParameter"):
                if user:
                    item1 = QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
                    item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    widget.setItem(row, 2, QTableWidgetItem("USER"))
                    widget.setItem(row, 3, QTableWidgetItem(""))
                    widget.setItem(row, 4, QTableWidgetItem(""))
                    widget.setItem(row, 5, QTableWidgetItem(""))
                    widget.setItem(row, 6, QTableWidgetItem(""))
                else:
                    if element.findtext("{http://tempuri.org/DataSet1.xsd}SoilTextureK") == value :
                        item1 = QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
                        item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                        widget.setItem(row, 2, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode")))
                        widget.setItem(row, 3, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}PorosityDefault")))
                        widget.setItem(row, 4, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}EffectivePorosityDefault")))
                        widget.setItem(row, 5, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}WFSoilSuctionHeadDefault")))
                        widget.setItem(row, 6, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}HydraulicConductivity")))
                        break

                    elif element.findtext("{http://tempuri.org/DataSet1.xsd}SoilTextureE") == value :
                        item1 = QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
                        item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                        widget.setItem(row, 2, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode")))
                        widget.setItem(row, 3, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}PorosityDefault")))
                        widget.setItem(row, 4, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}EffectivePorosityDefault")))
                        widget.setItem(row, 5, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}WFSoilSuctionHeadDefault")))
                        widget.setItem(row, 6, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}HydraulicConductivity")))
                        break

                    elif element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode") == value :
                        item1 = QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
                        item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                        widget.setItem(row, 2, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode")))
                        widget.setItem(row, 3, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}PorosityDefault")))
                        widget.setItem(row, 4, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}EffectivePorosityDefault")))
                        widget.setItem(row, 5, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}WFSoilSuctionHeadDefault")))
                        widget.setItem(row, 6, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}HydraulicConductivity")))
                        break

        elif type == "SoilDepth":
            for element in root.findall("{http://tempuri.org/DataSet1.xsd}SoilDepthParameter"):
                if user:
                    item1 = QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
                    item1.setFlags(Qt.ItemIsEnabled |Qt.ItemIsSelectable)
                    widget.setItem(row, 2,QTableWidgetItem("USER"))
                    widget.setItem(row, 3, QTableWidgetItem(""))
                    break
                else:
                    if element.findtext("{http://tempuri.org/DataSet1.xsd}SoilDepthClassK") == value :
                        item1 = QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
                        item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                        widget.setItem(row, 2,QTableWidgetItem(item1))
                        widget.setItem(row, 3, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}SoilDepthDefault")))
                        break
                    elif element.findtext("{http://tempuri.org/DataSet1.xsd}SoilDepthClassE") == value :
                        item1 = QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
                        item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                        widget.setItem(row, 2,QTableWidgetItem(item1))
                        widget.setItem(row, 3, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}SoilDepthDefault")))
                        break
                    elif element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode") == value :
                        item1 = QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
                        item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                        widget.setItem(row, 2,QTableWidgetItem(item1))
                        widget.setItem(row, 3, QTableWidgetItem(element.findtext("{http://tempuri.org/DataSet1.xsd}SoilDepthDefault")))
                        break
    def closeForm(self):
        self.close()  # 폼 종료


    # 초기 모든 변수값 셋팅 (프로젝트 파일에서 값을 읽어서 초기 셋팅 값을 결정함)
    def SetProjectValue(self):
        self.LandCoverType  =self._xmltodict['GRMProject']['ProjectSettings']['LandCoverDataType']
        self.SoilTextureType=self._xmltodict['GRMProject']['ProjectSettings']['SoilTextureDataType']
        self.SoilDepthType  =self._xmltodict['GRMProject']['ProjectSettings']['SoilDepthDataType']


        #그룹 박스 타이틀 부분 공백 줄이기
        self.grp1.setStyleSheet("QGroupBox{padding-top:15px;margin-top:-15px;}")
        self.grp_2.setStyleSheet("QGroupBox{padding-top:15px;margin-top:-15px;}")
        self.groupBox_3.setStyleSheet("QGroupBox{padding-top:15px;margin-top:-15px;}")
        self.groupBox_4.setStyleSheet("QGroupBox{padding-top:15px;margin-top:-15px;}")
        self.groupBox_5.setStyleSheet("QGroupBox{padding-top:15px;margin-top:-15px;}")
        self.groupBox_6.setStyleSheet("QGroupBox{padding-top:15px;margin-top:-15px;}")


    # 콤보 박스에 레이어 목록 넣어 두기
    def SetLayerListCombobox(self):
        # 콤보 박스 레이어 받아 오기 설정
        layers = QgsProject.instance().mapLayers().values()

        if (self._grmDialogFlag==1):
            lly=list(layers)
            remove_set=QgsProject.instance().mapLayersByName('WSFAlayerload')
            layers = [i for i in lly if i not in remove_set]
            
        SetCommbox(layers, self.cmbLandCover, "")
        SetCommbox(layers, self.cmbSoilTexture, "")
        SetCommbox(layers, self.cmbSoilDepth, "")


# 라디오 버튼 셋팅
    def SetRadio(self):
        try:
            # Lanccover 첫번째 라디오 버튼 클릭 이벤트 처리
            self.rbtUseLCLayer.clicked.connect(self.LCLaye_CheckedChanged)

            # Lanccover 두번째 라디오 버튼 클릭 이벤트 처리
            self.rbtUseConstLCAtt.clicked.connect(self.ConstLCAtt_CheckedChanged)

            # SoilTexture 첫번째 라디오 버튼 클릭 이벤트 처리
            self.rbtUseSoilTextureLayer.clicked.connect(self.SoilTextureLayer_CheckedChanged)

            # SoilTexture 두번째 라디오 버튼 클릭 이벤트 처리
            self.rbtUseConstTextureAtt.clicked.connect(self.TextureAtt_CheckedChanged)

            # SoilDepth  첫번째 라디오 버튼 클릭 이벤트 처리
            self.rbtUseSoilDepthLayer.clicked.connect(self.SoilDepthLayer_CheckedChanged)

            # SoilDepth  두번째 라디오 버튼 클릭 이벤트 처리
            self.rbtUseConstDepth.clicked.connect(self.ConstDepth_CheckedChanged)


            # ------------------------Lndcover 라디오 버튼 셋팅 시작---------------------------------
            #2017/11/27 =====
        
            if self.LandCoverType == "File":
                # 라디오 버튼 클릭시 활성, 비활성 컨트롤 함수
                self.LCLaye_CheckedChanged()

                # 라디오 버튼 체크 상태로 변환
                self.rbtUseLCLayer.setChecked(True)

                # 텍스트 파일에 Vat 파일 경로를 셋팅
                self.txtLandCover.setText(self._xmltodict['GRMProject']['ProjectSettings']['LandCoverVATFile'])

                # 콤보 박스의 선택 레이어를 프로젝트 파일에 있는 것으로 셋팅
                LandCoverFile = self._xmltodict['GRMProject']['ProjectSettings']['LandCoverFile']
                if LandCoverFile != "" and LandCoverFile is not None:
                    LandCoverName = GetFile_Name(LandCoverFile)
                    SetCommbox2(self.cmbLandCover, LandCoverName, LandCoverFile)
            else :
                # 2번째 라디오 버튼 클릭시 이벤트 함수
                self.ConstLCAtt_CheckedChanged()

                # 2번째 라디오 버튼 체크 상태로 변환
                self.rbtUseConstLCAtt.setChecked(True)

                # 사용자 일괄 적용 라디오 버튼 클릭시 적용 할 텍스트 박스의 값을 셋팅
                self.txtCoefficient.setText(self._xmltodict['GRMProject']['ProjectSettings']['ConstantRoughnessCoeff'])
                self.txtImpervious.setText(self._xmltodict['GRMProject']['ProjectSettings']['ConstantImperviousRatio'])
            # ------------------------Lndcover 라디오 버튼 셋팅 종료----------------------------------

            # ------------------------SoilTextureVATFile 라디오 버튼 셋팅 시작---------------------------------
            # SoilTextureVATFile 이벤트
            if self.SoilTextureType== "File":
                # SoilTextureVATFile 항목의 첫번째 라디오 버튼 클릭 이벤트(컨트롤 활성, 비활성 기능 연동)
                self.SoilTextureLayer_CheckedChanged()
            
                # 라디오 버튼 클릭 상태로 셋팅
                self.rbtUseSoilTextureLayer.setChecked(True)
            
                # 텍스트 박스에 VAT 파일 경로 넣기
                self.txtSoilTexture.setText(self._xmltodict['GRMProject']['ProjectSettings']['SoilTextureVATFile'])
            
                # layer 콤보 박스 항목을 프로젝트 파일의 데이터 내용에 해당되는 콤보 박스 항목으로 셋팅
                SoilTextureFile = self._xmltodict['GRMProject']['ProjectSettings']['SoilTextureFile']
                if SoilTextureFile != "" and SoilTextureFile is not None:
                    SoilTextureName = GetFile_Name(SoilTextureFile)
                    SetCommbox2(self.cmbSoilTexture, SoilTextureName, SoilTextureFile)
            else:
                # 2번째 라디오 버튼(일괄 적용) 클릭 이벤트
                self.TextureAtt_CheckedChanged()
  
                # 라디오 버튼 클릭 상태로 설정
                self.rbtUseConstTextureAtt.setChecked(True)
            
  
                # 프로젝트 파일에서 각각 텍스트 값을 입력
                self.txtPorosity.setText(self._xmltodict['GRMProject']['ProjectSettings']['ConstantSoilPorosity'])
                self.txtEffective_porosity.setText(
                    self._xmltodict['GRMProject']['ProjectSettings']['ConstantSoilEffPorosity'])
                self.txtSuction_head.setText(
                    self._xmltodict['GRMProject']['ProjectSettings']['ConstantSoilWettingFrontSuctionHead'])
                self.txtConductiovity.setText(
                    self._xmltodict['GRMProject']['ProjectSettings']['ConstantSoilHydraulicConductivity'])
        
  
            # ------------------------SoilTextureVATFile 라디오 버튼 셋팅 종료----------------------------------
  
  
            # ------------------------SoilDepth 라디오 버튼 셋팅 시작----------------------------------
            if self.SoilDepthType== "File":
  
                # SoilDepth 항목의 첫번째 체크 박스 선택 이벤트 함수
                self.SoilDepthLayer_CheckedChanged()
  
                # SoilDepth 항목의 첫번째 라디오 버튼 클릭 상태로 설정
                self.rbtUseSoilDepthLayer.setChecked(True)
  
                # 텍스트 박스에 VAT 파일 경로 넣기
                self.txtSoilDepth.setText(self._xmltodict['GRMProject']['ProjectSettings']['SoilDepthVATFile'])
  
                # layer 콤보 박스 항목을 프로젝트 파일의 데이터 내용에 해당되는 콤보 박스 항목으로 셋팅
                SoilDepthFile = self._xmltodict['GRMProject']['ProjectSettings']['SoilDepthFile']
                if SoilDepthFile != "" and SoilDepthFile is not None:
                    SoilDepthName = GetFile_Name(SoilDepthFile)
                    SetCommbox2(self.cmbSoilDepth, SoilDepthName, SoilDepthFile)
            else :
  
                # SoilDepth 항목의 두번째 체크 박스 선택 이벤트 함수
                self.ConstDepth_CheckedChanged()
  
                # SoilDepth 항목의 두번째 라디오 버튼 클릭 상태로 설정
                self.rbtUseConstDepth.setChecked(True)
  
                # 프로젝트 파일에서 값읽어서 텍스트 박스에 셋팅
                self.txtSoil_depth.setText(self._xmltodict['GRMProject']['ProjectSettings']['ConstantSoilDepth'])
        except Exception as e:
            MsError(e)

    # LandCover 첫번째 라이디오 버튼 클릭시 이벤트 처리
    def LCLaye_CheckedChanged(self):
        self.btnVatLand.setEnabled(True)
        self.txtLandCover.setEnabled(True)
        self.cmbLandCover.setEnabled(True)
        self.tlbLandCover.setEnabled(True)
        self.txtCoefficient.setEnabled(False)
        self.txtImpervious.setEnabled(False)

    # LandCover 두번째 라이디오 버튼 클릭시 이벤트 처리
    def ConstLCAtt_CheckedChanged(self):
        self.btnVatLand.setEnabled(False)
        self.txtLandCover.setEnabled(False)
        self.cmbLandCover.setEnabled(False)
        self.tlbLandCover.setEnabled(False)
        self.txtCoefficient.setEnabled(True)
        self.txtImpervious.setEnabled(True)

    # SoilTexture 첫번째 라디오 버튼 클릭 이벤트 처리
    def SoilTextureLayer_CheckedChanged(self):
        self.cmbSoilTexture.setEnabled(True)
        self.txtSoilTexture.setEnabled(True)
        self.btnVatAmpt.setEnabled(True)
        self.tblGreenAmpt.setEnabled(True)
        self.txtPorosity.setEnabled(False)
        self.txtEffective_porosity.setEnabled(False)
        self.txtSuction_head.setEnabled(False)
        self.txtConductiovity.setEnabled(False)

    # SoilTexture 두번째 라디오 버튼 클릭 이벤트 처리
    def TextureAtt_CheckedChanged(self):
        self.cmbSoilTexture.setEnabled(False)
        self.txtSoilTexture.setEnabled(False)
        self.btnVatAmpt.setEnabled(False)
        self.tblGreenAmpt.setEnabled(False)
        self.txtPorosity.setEnabled(True)
        self.txtEffective_porosity.setEnabled(True)
        self.txtSuction_head.setEnabled(True)
        self.txtConductiovity.setEnabled(True)

    # SoilDepth  첫번째 라디오 버튼 클릭 이벤트 처리
    def SoilDepthLayer_CheckedChanged(self):
        self.cmbSoilDepth.setEnabled(True)
        self.txtSoilDepth.setEnabled(True)
        self.btnVatDepth.setEnabled(True)
        self.tblSoilDepth.setEnabled(True)
        self.txtSoil_depth.setEnabled(False)
    # SoilDepth  두번째 라디오 버튼 클릭 이벤트 처리
    def ConstDepth_CheckedChanged(self):
        self.cmbSoilDepth.setEnabled(False)
        self.txtSoilDepth.setEnabled(False)
        self.btnVatDepth.setEnabled(False)
        self.tblSoilDepth.setEnabled(False)
        self.txtSoil_depth.setEnabled(True)


    # ====================각각의 테이블 헤더 셋팅 ======================================================================
    def SetTableHeader(self):
        self.SetLandCoverHeader()
        
        self.SetGreenAmptHeader()
        
        self.SetSoilDepthHeader()
        
    # LandCover Table 헤더 셋팅
    def SetLandCoverHeader(self):
        self.tlbLandCover.setColumnCount(5)
        self.tlbLandCover.setHorizontalHeaderLabels(
            ['GridValue', 'UserLandCover', 'GRMCode', 'RoughnessCoefficient',
             'ImperviousRatio'])

    # GreenAmpt Table 헤더 셋팅
    def SetGreenAmptHeader(self):
        self.tblGreenAmpt.setColumnCount(7)
        self.tblGreenAmpt.setHorizontalHeaderLabels(
            ['GridValue', 'USERSoil', 'GRMCode', 'Porosity', 'EffectivePorosity',
             'WFSoilSuctionHead', 'HydraulicConductivity'])

    # SoilDepth 테이블 헤더 셋팅
    def SetSoilDepthHeader(self):
        self.tblSoilDepth.setColumnCount(4)
        self.tblSoilDepth.setHorizontalHeaderLabels(
            ['GridValue', 'UserDepthClass', 'GRMCode', 'SoilDepth'])

    # 테이블에 데이터 값 넣기
    def SetTableData(self):
        # 1순위 프로젝트 파일내 데이터 값
        # 2순위 Vat 파일 셋팅

        if self.LandCoverType =="File" and self._LandCoverCount!= 0:
            self.SetLandCoverTalbe()

        if self.SoilTextureType=="File" and self._GreenAmptCount!=0:
            self.SetGreenAmptTalbe()

        if self.SoilDepthType=="File" and self._SoilDepthCount!= 0:
            self.SetSoilDepthTalbe()


    def SetLandCoverTalbe(self):
        try:

            # 프로젝트 파일에서 불러온 데이터 테이블에 셋팅
            if self._LandCoverCount >1:
                row = 0
                for artikel in self._xmltodict['GRMProject']['LandCover']:
                    self.tlbLandCover.insertRow(row)

                    item1 = QTableWidgetItem(artikel['GridValue'])
                    item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tlbLandCover.setItem(row, 0, QTableWidgetItem(item1))

                    item2 = QTableWidgetItem(artikel['UserLandCover'])
                    item2.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tlbLandCover.setItem(row, 1, QTableWidgetItem(item2))

                    item3 = QTableWidgetItem(artikel['GRMCode'])
                    item3.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tlbLandCover.setItem(row, 2, QTableWidgetItem(item3))

                    self.tlbLandCover.setItem(row, 3, QTableWidgetItem(artikel['RoughnessCoefficient']))
                    self.tlbLandCover.setItem(row, 4, QTableWidgetItem(artikel['ImperviousRatio']))
                    row = row + 1
            elif self._LandCoverCount ==1:
                    self.tlbLandCover.insertRow(0)

                    item1 = QTableWidgetItem(self._xmltodict['GRMProject']['LandCover']['GridValue'])
                    item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tlbLandCover.setItem(row, 0, QTableWidgetItem(item1))

                    item2 = QTableWidgetItem(self._xmltodict['GRMProject']['LandCover']['UserLandCover'])
                    item2.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tlbLandCover.setItem(row, 1, QTableWidgetItem(item2))

                    item3 = QTableWidgetItem(self._xmltodict['GRMProject']['LandCover']['GRMCode'])
                    item3.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tlbLandCover.setItem(row, 2, QTableWidgetItem(item3))

                    self.tlbLandCover.setItem(row, 3, QTableWidgetItem(self._xmltodict['GRMProject']['LandCover']['RoughnessCoefficient']))
                    self.tlbLandCover.setItem(row, 4, QTableWidgetItem(self._xmltodict['GRMProject']['LandCover']['ImperviousRatio']))
            elif self._LandCoverCount ==0:

                if self.cmbLandCover.currentIndex()!=0:
                    self.Get_ComboBox_LayerPath(self.cmbLandCover,self.tlbLandCover,self.txtLandCover,"LandCover")


        except KeyError:
            self.Get_ComboBox_LayerPath(self.cmbLandCover, self.tlbLandCover, self.txtLandCover, "LandCover")


    def SetGreenAmptTalbe(self):
        try:
            # 프로젝트 파일에서 불러온 데이터 테이블에 셋팅
            if self._GreenAmptCount >1:
                row = 0
                for artikel in self._xmltodict['GRMProject']['GreenAmptParameter']:
                    self.tblGreenAmpt.insertRow(row)

                    item1 = QTableWidgetItem(artikel['GridValue'])
                    item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tblGreenAmpt.setItem(row, 0, QTableWidgetItem(item1))

                    item2 = QTableWidgetItem(artikel['USERSoil'])
                    item2.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tblGreenAmpt.setItem(row, 1, QTableWidgetItem(item2))

                    item3 = QTableWidgetItem(artikel['GRMCode'])
                    item3.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tblGreenAmpt.setItem(row, 2, QTableWidgetItem(item3))

                    self.tblGreenAmpt.setItem(row, 3, QTableWidgetItem(artikel['Porosity']))
                    self.tblGreenAmpt.setItem(row, 4, QTableWidgetItem(artikel['EffectivePorosity']))
                    self.tblGreenAmpt.setItem(row, 5, QTableWidgetItem(artikel['WFSoilSuctionHead']))
                    self.tblGreenAmpt.setItem(row, 6, QTableWidgetItem(artikel['HydraulicConductivity']))
                    row = row + 1
            elif self._GreenAmptCount ==1:
                    self.tblGreenAmpt.insertRow(0)

                    item1 = QTableWidgetItem(self._xmltodict['GRMProject']['GreenAmptParameter']['GridValue'])
                    item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tblGreenAmpt.setItem(row, 0, QTableWidgetItem(item1))

                    item2 = QTableWidgetItem(self._xmltodict['GRMProject']['GreenAmptParameter']['USERSoil'])
                    item2.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tblGreenAmpt.setItem(row, 1, QTableWidgetItem(item2))

                    item3 = QTableWidgetItem(self._xmltodict['GRMProject']['GreenAmptParameter']['GRMCode'])
                    item3.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tblGreenAmpt.setItem(row, 2, QTableWidgetItem(item3))

                    self.tblGreenAmpt.setItem(row, 3, QTableWidgetItem(self._xmltodict['GRMProject']['GreenAmptParameter']['Porosity']))
                    self.tblGreenAmpt.setItem(row, 4, QTableWidgetItem(self._xmltodict['GRMProject']['GreenAmptParameter']['EffectivePorosity']))
                    self.tblGreenAmpt.setItem(row, 5, QTableWidgetItem(self._xmltodict['GRMProject']['GreenAmptParameter']['WFSoilSuctionHead']))
                    self.tblGreenAmpt.setItem(row, 6, QTableWidgetItem(self._xmltodict['GRMProject']['GreenAmptParameter']['HydraulicConductivity']))

        except KeyError:
            self.Get_ComboBox_LayerPath(self.cmbSoilTexture, self.tblGreenAmpt, self.txtSoilTexture,"GreenAmpt")

    def SetSoilDepthTalbe(self):
        try:
            # 프로젝트 파일에서 불러온 데이터 테이블에 셋팅
            if self._SoilDepthCount > 1:
                row = 0
                for artikel in self._xmltodict['GRMProject']['SoilDepth']:
                    self.tblSoilDepth.insertRow(row)

                    item1 = QTableWidgetItem(artikel['GridValue'])
                    item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tblSoilDepth.setItem(row, 0, QTableWidgetItem(item1))

                    item2 = QTableWidgetItem(artikel['UserDepthClass'])
                    item2.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tblSoilDepth.setItem(row, 1, QTableWidgetItem(item2))

                    item3 = QTableWidgetItem(artikel['GRMCode'])
                    item3.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                    self.tblSoilDepth.setItem(row, 2, QTableWidgetItem(item3))

                    item4 = QTableWidgetItem(artikel['SoilDepth_cm'])
                    self.tblSoilDepth.setItem(row, 3, QTableWidgetItem(item4))
                    row = row + 1

            elif  self._SoilDepthCount == 1:
                self.tblSoilDepth.insertRow(0)

                item1 = QTableWidgetItem(self._xmltodict['GRMProject']['SoilDepth']['GridValue'])
                item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                self.tblSoilDepth.setItem(row, 0, QTableWidgetItem(item1))

                item2 = QTableWidgetItem(self._xmltodict['GRMProject']['SoilDepth']['UserDepthClass'])
                item2.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                self.tblSoilDepth.setItem(row, 1, QTableWidgetItem(item2))

                item3 = QTableWidgetItem(self._xmltodict['GRMProject']['SoilDepth']['GRMCode'])
                item3.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                self.tblSoilDepth.setItem(row, 2, QTableWidgetItem(item3))

                item4 = QTableWidgetItem(self._xmltodict['GRMProject']['SoilDepth']['SoilDepth_cm'])
                self.tblSoilDepth.setItem(row, 3, QTableWidgetItem(item4))
        except Exception as e:
            self.Get_ComboBox_LayerPath(self.cmbSoilDepth, self.tblSoilDepth, self.txtSoilDepth, "SoilDepth")
            MsError(e)


    # Qdilog 창에 Qtablewidget 셋팅
    def aboutApp(self, type, row): 
        global _SelectRow
        _SelectRow= row
        website = "http://code.google.com/p/comictagger"
        email = "comictagger@gmail.com"
        license_link = "http://www.apache.org/licenses/LICENSE-2.0"
        license_name = "Apache License 2.0"
        Project = "test"
        msgBox = QMessageBox()
        msgBox.setWindowTitle(self.tr("Select Attribute"))
        msgBox.setTextFormat(Qt.RichText)
        msgBox.setIconPixmap(QPixmap(Project))
        msgBox.setText("<br><br><br><br><br><br><br><br><br><br><br>" + "<font color=white>" +
                       "{0},{1},{2}</font>".format(website, email, license_name))
        self.addTableWidget(msgBox,type)
        msgBox.exec_()


    #Create TableWidget
    def addTableWidget (self, parentItem,type) :
        self.tableWidget = QTableWidget(parentItem)
        self.tableWidget.setGeometry(QRect(0, 0, 500, 250))
        self.tableWidget.setObjectName ('tableWidget')
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.paranet = parentItem
        if type =="LandCover":
            self.SetLandcoverTable(self.tableWidget)
        if type =="GreenAmpt":
            self.SetGreenAmptTable(self.tableWidget)
        if type=="SoilDepth" :
            self.SetSoilDepth(self.tableWidget)


    # 더블 클릭시 Qdialog 에 테이블 셋팅 하기
    def SetLandcoverTable(self,tableWidget):
        doc = ET.parse(self.StaticDB)
        root = doc.getroot()
        list = []
        for element in root.findall('{http://tempuri.org/DataSet1.xsd}LandCoverParameter'):
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}LandCoverE"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}LandCoverK"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}RoughnessCoefficient"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}ImperviousRatio"))
 
        # table에 값 셋팅
        tableWidget.verticalHeader().hide()
        tableWidget.setColumnCount(5)

        value=int(len(list) / 5)
        tableWidget.setRowCount(value)
        tableWidget.setHorizontalHeaderLabels(
            [  'LandCoverE', 'LandCoverK','GRMCode','RoughnessCoefficient','ImperviousRatio'])
 
        tableWidget.resizeColumnsToContents()
        tableWidget.resizeRowsToContents()
        tableWidget.itemDoubleClicked.connect(lambda: self.SelectCellValue(tableWidget, "LandCover"))
        # 각각의 컬럼에 갑셋팅(xml 상에 'ObTSId', 'ObTSLegend', 'ObTSMissingCount' 항목의 값이 없음
        for i in range(0, value):
            for j in range(0, 5):
                self.tableWidget.setItem(i, j, QTableWidgetItem(list[5 * i + j]))

    def SetGreenAmptTable(self,tableWidget):
        # 프로젝트 파일 로드
        doc = ET.parse(self.StaticDB)

        root = doc.getroot()
        list = []
        for element in root.findall("{http://tempuri.org/DataSet1.xsd}GreenAmptSoilParameter"):
            
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}SoilTextureE"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}SoilTextureK"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}PorosityMin"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}PorosityMax"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}PorosityDefault"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}EffectivePorosityMin"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}EffectivePorosityMax"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}EffectivePorosityDefault"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}ResidualMoistureContent"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}WFSoilSuctionHeadMin"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}WFSoilSuctionHeadMax"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}WFSoilSuctionHeadDefault"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}HydraulicConductivity"))
            

        # table에 값 셋팅
        tableWidget.verticalHeader().hide()
        tableWidget.setColumnCount(14)

        value= int(len(list) / 14)
        tableWidget.setRowCount(value)
        tableWidget.setHorizontalHeaderLabels(
            ['SoilTextureE', 'SoilTextureK', 'GRMCode', 'PorosityMin', 'PorosityMax', 'PorosityDefault', 'EffectivePorosityMin',
             'EffectivePorosityMax', 'EffectivePorosityDefault','ResidualMoistureContent','WFSoilSuctionHeadMin',
             'WFSoilSuctionHeadMax','WFSoilSuctionHeadDefault','HydraulicConductivity'])
 
        tableWidget.resizeColumnsToContents()
        tableWidget.resizeRowsToContents()
        tableWidget.itemDoubleClicked.connect(lambda : self.SelectCellValue(tableWidget,"GreenAmpt"))

        # 각각의 컬럼에 갑셋팅(xml 상에 'ObTSId', 'ObTSLegend', 'ObTSMissingCount' 항목의 값이 없음
        for i in range(0, value):
            for j in range(0, 14):
                self.tableWidget.setItem(i, j, QTableWidgetItem(list[14 * i + j]))


    def SetSoilDepth(self, tableWidget):
        doc = ET.parse(self.StaticDB)

        root = doc.getroot()
        list = []
        for element in root.findall("{http://tempuri.org/DataSet1.xsd}SoilDepthParameter"):
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}GRMCode"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}SoilDepthClassE"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}SoilDepthClassK"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}SoilDepthMin"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}SoilDepthMax"))
            list.append(element.findtext("{http://tempuri.org/DataSet1.xsd}SoilDepthDefault"))

        # table에 값 셋팅
        tableWidget.verticalHeader().hide()
        tableWidget.setColumnCount(6)

        value= int(len(list) / 6)

        tableWidget.setRowCount(value)
        tableWidget.setHorizontalHeaderLabels(
            ['GRMCode', 'SoilDepthClassE', 'SoilDepthClassK', 'SoilDepthMin','SoilDepthMax','SoilDepth'])

        tableWidget.resizeColumnsToContents()
        tableWidget.resizeRowsToContents()
        tableWidget.itemDoubleClicked.connect(lambda: self.SelectCellValue(tableWidget, "SoilDepth"))
        # 각각의 컬럼에 갑셋팅(xml 상에 'ObTSId', 'ObTSLegend', 'ObTSMissingCount' 항목의 값이 없음
        for i in range(0, value):
            for j in range(0, 6):
                self.tableWidget.setItem(i, j, QTableWidgetItem(list[6 * i + j]))



    #작은 창 테이블 클릭시 큰 테이블에 선택값 셋팅(집중이 안되서 노가다함 ㅠㅠ)
    #2020-01-15 박: 사용자 지정은 타이틀은 바뀌지 않게 되어 있는데 이거 변경 하게 하는지 최박사님께 문의 하도록 
    def SelectCellValue(self, tableWidget,type):
        row = tableWidget.currentRow()
        try:
            items = []
            
            if type=="LandCover":
                item2 = tableWidget.item(row, 0)
                item3 = tableWidget.item(row, 1)
                item4 = tableWidget.item(row, 2)
                item5 = tableWidget.item(row, 3)
                item6 = tableWidget.item(row, 4)
                
                items = [item4, item5, item6]
                tbl = self.tlbLandCover
                
                #self.tlbLandCover.item(_SelectRow, 1).setText(item3.text())
#                 self.tlbLandCover.item(_SelectRow, 2).setText(item4.text())
#                 self.tlbLandCover.item(_SelectRow, 3).setText(item5.text())
#                 self.tlbLandCover.item(_SelectRow, 4).setText(item6.text())
                # 메시지 박스 종료
#                 self.paranet.done(1)
    
            elif type=="GreenAmpt":
                item2 = tableWidget.item(row, 0)
                item3 = tableWidget.item(row, 1)
                item4 = tableWidget.item(row, 2)
                item5 = tableWidget.item(row, 5)
                item6 = tableWidget.item(row, 8)
                item7 = tableWidget.item(row, 12)
                item8 = tableWidget.item(row, 13)
                
                items = [item4, item5, item6, item7, item8]
                tbl = self.tblGreenAmpt
    
                #self.tblGreenAmpt.item(_SelectRow, 1).setText(item3.text())
#                 self.tblGreenAmpt.item(_SelectRow, 2).setText(item4.text())
#                 self.tblGreenAmpt.item(_SelectRow, 3).setText(item5.text())
#                 self.tblGreenAmpt.item(_SelectRow, 4).setText(item6.text())
#                 self.tblGreenAmpt.item(_SelectRow, 5).setText(item7.text())
#                 self.tblGreenAmpt.item(_SelectRow, 6).setText(item8.text())
                    
                # 메시지 박스 종료
#                 self.paranet.done(1)
    
            elif type == "SoilDepth":
                item2 = tableWidget.item(row, 0)
                item3 = tableWidget.item(row, 1)
                item4 = tableWidget.item(row, 2)
                item5 = tableWidget.item(row, 5)
                
                items = [item2, item5]
                tbl = self.tblSoilDepth
                
#                 self.tblSoilDepth.item(_SelectRow, 2).setText(item2.text())
#                 self.tblSoilDepth.item(_SelectRow, 3).setText(item5.text())
            
            for i, it in enumerate(items):
                if tbl.item(_SelectRow, i+2):
                    tbl.item(_SelectRow, i+2).setText(it.text())
                else:
                    tbl.setItem(_SelectRow, i+2, QTableWidgetItem(it.text()))
            
                # 메시지 박스 종료
#                 self.paranet.done(1)
        except AttributeError as e:
            print(e) 
            MsError("This is not valid data.")
        finally:
            self.paranet.done(1)

    def DataSave(self):
        if self.rbtUseLCLayer.isChecked():
            self._xmltodict['GRMProject']['ProjectSettings']['LandCoverDataType'] ="File"
            if self.cmbLandCover.currentIndex()!=0:
                LandCoverLayerPath = GetcomboSelectedLayerPath(self.cmbLandCover)
            else :
                LandCoverLayerPath=""

            self._xmltodict['GRMProject']['ProjectSettings']['LandCoverFile'] =LandCoverLayerPath
            self._xmltodict['GRMProject']['ProjectSettings']['LandCoverVATFile'] = self.txtLandCover.text()
            self.dataSeve_Landcover()
        else :
            self._xmltodict['GRMProject']['ProjectSettings']['LandCoverDataType'] = "Constant"
            self._xmltodict['GRMProject']['ProjectSettings']['ConstantRoughnessCoeff'] = self.txtCoefficient.text()
            self._xmltodict['GRMProject']['ProjectSettings']['ConstantImperviousRatio'] = self.txtImpervious.text()

        #  타입 설정
        if self.rbtUseSoilTextureLayer.isChecked():
            self._xmltodict['GRMProject']['ProjectSettings']['SoilTextureDataType'] ="File"
            if self.cmbSoilTexture.currentIndex()!=0:
                SoilTextureLayerPath = GetcomboSelectedLayerPath(self.cmbSoilTexture)
            else:
                SoilTextureLayerPath=""
            self._xmltodict['GRMProject']['ProjectSettings']['SoilTextureFile'] =SoilTextureLayerPath
            self._xmltodict['GRMProject']['ProjectSettings']['SoilTextureVATFile']=self.txtSoilTexture.text()
            self.dataSeve_SoilTexture()
        else :
            self._xmltodict['GRMProject']['ProjectSettings']['SoilTextureDataType'] = "Constant"
            self._xmltodict['GRMProject']['ProjectSettings']['ConstantSoilPorosity'] = self.txtPorosity.text()
            self._xmltodict['GRMProject']['ProjectSettings']['ConstantSoilEffPorosity'] = self.txtEffective_porosity.text()
            self._xmltodict['GRMProject']['ProjectSettings']['ConstantSoilWettingFrontSuctionHead'] = self.txtSuction_head.text()
            self._xmltodict['GRMProject']['ProjectSettings']['ConstantSoilHydraulicConductivity'] = self.txtConductiovity.text()

        #  타입 설정
        if self.rbtUseSoilDepthLayer.isChecked():
            self._xmltodict['GRMProject']['ProjectSettings']['SoilDepthDataType'] ="File"

            if self.cmbSoilDepth.currentIndex() != 0:
                SoilDepthLayerPath = GetcomboSelectedLayerPath(self.cmbSoilDepth)
            else:
                SoilDepthLayerPath = ""
            self._xmltodict['GRMProject']['ProjectSettings']['SoilDepthFile']  = SoilDepthLayerPath
            self._xmltodict['GRMProject']['ProjectSettings']['SoilDepthVATFile'] = self.txtSoilDepth.text()
            self.dataSeve_SoilDepth()
        else :
            self._xmltodict['GRMProject']['ProjectSettings']['SoilDepthDataType'] = "Constant"
            self._xmltodict['GRMProject']['ProjectSettings']['ConstantSoilDepth'] = self.txtSoil_depth.text()



    def dataSeve_Landcover(self):
        try:
            # dictionary 에서 LandCover 항목을 모두 제거
            check = self._xmltodict['GRMProject']['LandCover']
            if check is not None:
                del self._xmltodict['GRMProject']['LandCover']
        except:
            pass


        # dictionary 에서 엘레먼트 생성이 안되서 dic===> XML (element 생성 ) ===> dictionary 변환
        #DictoXml = xmltodict.unparse(self._xmltodict)
        DictoXml = unparse(self._xmltodict)
        ET.register_namespace('', "http://tempuri.org/GRMProject.xsd")
        xmltree = ET.ElementTree(ET.fromstring(DictoXml))
        root = xmltree.getroot()
        count =self.tlbLandCover.rowCount()
        self._LandCoverCount = count

        try:
            for row in range(0, count):
                child = ET.Element("LandCover")
                root.append(child)

                GridValue = ET.Element("GridValue")
                #특수문자 있음 제외 함
                GridValue.text = self.tlbLandCover.item(row, 0).text().replace("﻿","")
                child.append(GridValue)

                UserLandCover = ET.Element("UserLandCover")
                UserLandCover.text = self.tlbLandCover.item(row, 1).text()
                child.append(UserLandCover)

                GRMLandCoverCode = ET.Element("GRMCode")
                GRMLandCoverCode.text = self.tlbLandCover.item(row, 2).text()
                child.append(GRMLandCoverCode)


                RoughnessCoefficient = ET.Element("RoughnessCoefficient")
                RoughnessCoefficient.text = self.tlbLandCover.item(row, 3).text()
                child.append(RoughnessCoefficient)

                ImperviousRatio = ET.Element("ImperviousRatio")
                ImperviousRatio.text = self.tlbLandCover.item(row, 4).text()
                child.append(ImperviousRatio)


            filepath = tempfile.mktemp()
            xmltree.write(filepath)

            # Dictionary 초기화
            self._xmltodict.clear()

            # 파일 읽어 오기
            Projectfile = open(filepath, 'r')
            data = Projectfile.read()
            Projectfile.close()
            # 읽어온 파일 내용(XML)을 dictionary 로 변경
            docs = dict(parse(data))
            self._xmltodict.update(docs)
        except Exception as e:
            pass

    def dataSeve_SoilTexture(self):
        # dictionary 에서 GreenAmptParameter 항목을 모두 제거
        try:
            # dictionary 에서 LandCover 항목을 모두 제거
            check = self._xmltodict['GRMProject']['GreenAmptParameter']
            if check is not None:
                del self._xmltodict['GRMProject']['GreenAmptParameter']
        except:
            pass

        # dictionary 에서 엘레먼트 생성이 안되서 dic===> XML (element 생성 ) ===> dictionary 변환
        #DictoXml = xmltodict.unparse(self._xmltodict)
        DictoXml = unparse(self._xmltodict)
        ET.register_namespace('', "http://tempuri.org/GRMProject.xsd")
        xmltree = ET.ElementTree(ET.fromstring(DictoXml))
        root = xmltree.getroot()
        count = self.tblGreenAmpt.rowCount()
        self._GreenAmptCount = count
        for row in range(0, count):
            child = ET.Element("GreenAmptParameter")
            root.append(child)

            GridValue = ET.Element("GridValue")
            #특수문자 있음 제외 함
            GridValue.text = self.tblGreenAmpt.item(row, 0).text().replace("﻿","")
            child.append(GridValue)

            USERSoil = ET.Element("USERSoil")
            USERSoil.text = self.tblGreenAmpt.item(row, 1).text()
            child.append(USERSoil)

            GRMCode = ET.Element("GRMCode")
            GRMCode.text = self.tblGreenAmpt.item(row, 2).text()
            child.append(GRMCode)

            Porosity = ET.Element("Porosity")
            Porosity.text = self.tblGreenAmpt.item(row, 3).text()
            child.append(Porosity)

            EffectivePorosity = ET.Element("EffectivePorosity")
            EffectivePorosity.text = self.tblGreenAmpt.item(row, 4).text()
            child.append(EffectivePorosity)

            WFSoilSuctionHead = ET.Element("WFSoilSuctionHead")
            WFSoilSuctionHead.text = self.tblGreenAmpt.item(row, 5).text()
            child.append(WFSoilSuctionHead)

            HydraulicConductivity = ET.Element("HydraulicConductivity")
            HydraulicConductivity.text = self.tblGreenAmpt.item(row, 6).text()
            child.append(HydraulicConductivity)

        # xmltree.write("C:\Users\hermesys\Desktop\Sct2.gmp")
        filepath = tempfile.mktemp()
        xmltree.write(filepath)

        # Dictionary 초기화
        self._xmltodict.clear()

        # 파일 읽어 오기
        Projectfile = open(filepath, 'r')
        data = Projectfile.read()
        Projectfile.close()
        # 읽어온 파일 내용(XML)을 dictionary 로 변경
        docs = dict(parse(data))
        self._xmltodict.update(docs)


    def dataSeve_SoilDepth(self):
        # dictionary 에서 GreenAmptParameter 항목을 모두 제거
        try:
            check = self._xmltodict['GRMProject']['SoilDepth']
            if check is not None:
                del self._xmltodict['GRMProject']['SoilDepth']
        except:
            pass

        # dictionary 에서 엘레먼트 생성이 안되서 dic===> XML (element 생성 ) ===> dictionary 변환
        DictoXml = unparse(self._xmltodict)
        ET.register_namespace('', "http://tempuri.org/GRMProject.xsd")
        xmltree = ET.ElementTree(ET.fromstring(DictoXml))
        root = xmltree.getroot()
        count = self.tblSoilDepth.rowCount()
        self._SoilDepthCount = count
        for row in range(0, count):
            child = ET.Element("SoilDepth")
            root.append(child)

            GridValue = ET.Element("GridValue")
            #특수문자 있음 제외 함
            GridValue.text = self.tblSoilDepth.item(row, 0).text().replace("﻿","")
            child.append(GridValue)

            UserDepthClass = ET.Element("UserDepthClass")
            UserDepthClass.text = self.tblSoilDepth.item(row, 1).text()
            child.append(UserDepthClass)

            GRMDepthCode = ET.Element("GRMCode")
            GRMDepthCode.text = self.tblSoilDepth.item(row, 2).text()
            child.append(GRMDepthCode)

            # SoilDepthClassE = ET.Element("SoilDepthClassE")
            # SoilDepthClassE.text = self.tblSoilDepth.item(row, 3).text()
            # child.append(SoilDepthClassE)
            #
            # SoilDepthClassK = ET.Element("SoilDepthClassK")
            # SoilDepthClassK.text = self.tblSoilDepth.item(row, 4).text()
            # child.append(SoilDepthClassK)

            SoilDepth = ET.Element("SoilDepth_cm")
            SoilDepth.text = self.tblSoilDepth.item(row, 3).text()
            child.append(SoilDepth)

        # xmltree.write("C:\Users\hermesys\Desktop\Sct2.gmp")
        filepath = tempfile.mktemp()
        xmltree.write(filepath)

        # Dictionary 초기화
        self._xmltodict.clear()

        # 파일 읽어 오기
        Projectfile = open(filepath, 'r')
        data = Projectfile.read()
        Projectfile.close()
        # 읽어온 파일 내용(XML)을 dictionary 로 변경
        docs = dict(parse(data))
        self._xmltodict.update(docs)



    def isFloat(self ,Snumber):
        try:
            float(Snumber)
            return True
        except ValueError:
            return False
