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

import sys
import os
from PyQt5 import uic,QtCore,QtWidgets
from PyQt5.QtWidgets import QDockWidget

#from PyQt5 import *
#from PyQt5 import *
#from PyQt5.QtWidgets import *

import re
import os.path
import win32api
import tempfile
from subprocess import Popen

from .xmltodict import *
from .lib.Util import *
from .XMLCheck import *
from xml.etree import ElementTree as ET


XMLCheck= xmls()
_xmltodict_Project={}
class Set_ProjectToControls(object):
    def __init__(self, dialog):
        global Dialog
        Dialog = dialog

    def Group_Enable(self):
        Dialog.groupBox_Main.setEnabled(True)

    def Check_Project_file(self,projectfile):
        try:
            global _xmltodict_Project, getset
            getset = XMLCheck.Check_Gmp_xml(projectfile)

            # 프로젝트 파일(XML)을 그냥 일반 문서 처럼 읽어옴
            Projectfile = open(projectfile, 'r')
            data = Projectfile.read()
            Projectfile.close()
            #읽어온 파일 내용(XML)을 dictionary 로 변경
            _xmltodict_Project = dict(parse(data))
            self.Setting_Control()
            return _xmltodict_Project
        except Exception as e:
            MsInfo(e)
    def Setting_Control(self):
        try:
            #global _xmltodict_Project
            #_xmltodict_Project = xmldic
            # Domain Group 
            


            Dialog.txt_dem.setText(_xmltodict_Project['projectds']['ProjectSettings']['DEMFile'])

            #Land Cover Group
            LandCoverFile = _xmltodict_Project['projectds']['ProjectSettings']['LandCoverFile']
            LandCoverVatFile = _xmltodict_Project['projectds']['ProjectSettings']['LandCoverVatFile']

            if (LandCoverFile != "" and  LandCoverFile != None) or (LandCoverVatFile != "" and  LandCoverVatFile != None) :
                Dialog.txt_landcover.setText(LandCoverFile)
                Dialog.txt_lcVat.setText(LandCoverVatFile)
                Dialog.rdo_Land_Cover.setChecked(True)
                self.Set_LandCover_Enable_Option() # Landcover 체크박스 옵션
            else:
                Dialog.txt_landcover.setText("")
                Dialog.txt_lcVat.setText("")
                Dialog.rdo_Land_Cover.setChecked(False)
                self.Set_LandCover_Enable_Option()
                 
            Dialog.txt_roughness.setText(_xmltodict_Project['projectds']['HydroPars']['RoughnessCoeff'])
            Dialog.txt_conditon_File.setText(_xmltodict_Project['projectds']['HydroPars']['InitialCondition'])

            InitialConditionType =_xmltodict_Project['projectds']['HydroPars']['InitialConditionType']
            if InitialConditionType =="Height":
                Dialog.cmb_ConditionType.setCurrentIndex(2)
            elif InitialConditionType =="Depth":
                Dialog.cmb_ConditionType.setCurrentIndex(1)
            else:
                Dialog.cmb_ConditionType.setCurrentIndex(0)

            Dialog.txt_Froud.setText(_xmltodict_Project['projectds']['HydroPars']['FroudeNumberCriteria'])
            Dialog.txt_courant.setText(_xmltodict_Project['projectds']['HydroPars']['CourantNumber'])
            Dialog.txt_slope.setText(_xmltodict_Project['projectds']['HydroPars']['DomainOutBedSlope'])

            flag_VNC=_xmltodict_Project['projectds']['HydroPars']['ApplyVNC']

            if str(flag_VNC).upper()=="TRUE":
                Dialog.chk_Apply_VNC.setChecked(True)
            else:
                Dialog.chk_Apply_VNC.setChecked(False)


            #Simulation settings Group
            flag =_xmltodict_Project['projectds']['ProjectSettings']['IsFixedDT']
            if str(flag).upper()=="TRUE":
                Dialog.chk_FixedDT.setChecked(True)
            else:
                Dialog.chk_FixedDT.setChecked(False)

            Dialog.spb_Starting_Cal_time.setValue(float(_xmltodict_Project['projectds']['ProjectSettings']['CalculationTimeInterval_sec']))


            #flag =_xmltodict_Project['projectds']['ProjectSettings']['IsParallel']
            #if str(flag).upper()=="TRUE":
            #    Dialog.chk_Parallel.setChecked(True)
            #else:
            #    Dialog.chk_Parallel.setChecked(False)

            flag =_xmltodict_Project['projectds']['ProjectSettings']['UsingGPU']
            if str(flag).upper()=="TRUE":
                Dialog.chk_Using_GPU.setChecked(True)
            else:
                Dialog.chk_Using_GPU.setChecked(False)
                self.Set_GPU()

            value =_xmltodict_Project['projectds']['ProjectSettings']['ThreadsPerBlock']
            Dialog.spb_GPU_ThreadsPerBlock.setValue(int(value))

            value =_xmltodict_Project['projectds']['ProjectSettings']['MaxIterationAllCells']
            Dialog.spb_CPU_GS.setValue(int(value))
            
            value =_xmltodict_Project['projectds']['ProjectSettings']['MaxIterationACell']
            Dialog.spb_CPU_NR.setValue(int(value))
            
            Parallel_value=_xmltodict_Project['projectds']['ProjectSettings']['MaxDegreeOfParallelismCPU']
            Dialog.spb_Parallel_value.setValue(int(Parallel_value))

            Starting_time_Value=_xmltodict_Project['projectds']['ProjectSettings']['StartDateTime']

            if Starting_time_Value=="0":
                Dialog.chk_Starting_time.setChecked(False)
                self.Set_Starting_time()
            else:
                Dialog.chk_Starting_time.setChecked(True)
                self.Set_Starting_time()
                date=Starting_time_Value.replace("-","/").replace(":","/").replace(" ","/")
                date_list = date.split("/")
                
                someDT = QtCore.QDateTime(int(date_list[0]),int(date_list[1]),int(date_list[2]),int(date_list[3]),int(date_list[4]))
   
                Dialog.dte_Starting_time.setDateTime(someDT)

            Simulation_Hour=_xmltodict_Project['projectds']['ProjectSettings']['SimulationDuration_hr']
            Dialog.spb_Simulation_Hour.setValue(int(Simulation_Hour))

            # Output options Group
            interval_value =_xmltodict_Project['projectds']['ProjectSettings']['PrintoutInterval_min']
            Dialog.spb_Output_Step.setValue(int(interval_value))

            Dialog.chk_wdepth.setDisabled(False)
            Dialog.chk_waterLevel.setDisabled(False)
            Dialog.chk_velocity.setDisabled(False)
            Dialog.chk_discharge.setDisabled(False)
            Dialog.chk_direction.setDisabled(False)

            Make_Asc=_xmltodict_Project['projectds']['ProjectSettings']['MakeASCFile']
            if str(Make_Asc).upper()=="TRUE":
                Dialog.chk_makeASCII.setChecked(True)
            else:
                Dialog.chk_makeASCII.setChecked(False)

            Make_Img=_xmltodict_Project['projectds']['ProjectSettings']['MakeImgFile']
            if str(Make_Img).upper()=="TRUE":
                Dialog.chk_makeimg.setChecked(True)
            else:
                Dialog.chk_makeimg.setChecked(False)

                #Dialog.chk_wdepth.setDisabled(True)
                #Dialog.chk_waterLevel.setDisabled(True)
                #Dialog.chk_velocity.setDisabled(True)
                #Dialog.chk_discharge.setDisabled(True)
                #Dialog.chk_direction.setDisabled(True)

                Dialog.spb_maxRenDepth.setDisabled(True)
                Dialog.spb_maxRenLevel.setDisabled(True)
                Dialog.spb_maxRenVelocity.setDisabled(True)
                Dialog.spb_maxRenDischarge.setDisabled(True)
                #Dialog.chk_Rainfall.setDisabled(True)
                #Dialog.spb_Rainfall.setDisabled(True)

            check_bool=_xmltodict_Project['projectds']['ProjectSettings']['OutputDepth']
            if str(check_bool).upper()=="TRUE":
                Dialog.chk_wdepth.setChecked(True)
            else:
                Dialog.chk_wdepth.setChecked(False)
            check_value=_xmltodict_Project['projectds']['ProjectSettings']['DepthImgRendererMaxV']
            Dialog.spb_maxRenDepth.setValue(float(check_value))
            check_value=_xmltodict_Project['projectds']['ProjectSettings']['OutputPrecision_Depth']
            Dialog.spb_oPrecision_Depth.setValue(float(check_value))    


            check_bool=_xmltodict_Project['projectds']['ProjectSettings']['OutputWaterLevel']
            if str(check_bool).upper()=="TRUE":
                Dialog.chk_waterLevel.setChecked(True)
            else:
                Dialog.chk_waterLevel.setChecked(False)
            check_value=_xmltodict_Project['projectds']['ProjectSettings']['WaterLevelimgRendererMaxV']
            Dialog.spb_maxRenLevel.setValue(float(check_value))    
            check_value=_xmltodict_Project['projectds']['ProjectSettings']['OutputPrecision_WaterLevel']
            Dialog.spb_oPrecision_WaterLevel.setValue(float(check_value))      


            check_bool=_xmltodict_Project['projectds']['ProjectSettings']['OutputVelocityMax']
            if str(check_bool).upper()=="TRUE":
                Dialog.chk_velocity.setChecked(True)
            else:
                Dialog.chk_velocity.setChecked(False)
            check_value=_xmltodict_Project['projectds']['ProjectSettings']['VelocityMaxImgRendererMaxV']
            Dialog.spb_maxRenVelocity.setValue(float(check_value))
            check_value=_xmltodict_Project['projectds']['ProjectSettings']['OutputPrecision_VelocityMax']
            Dialog.spb_oPrecision_Velocity.setValue(float(check_value))    
            
            check_bool=_xmltodict_Project['projectds']['ProjectSettings']['OutputDischargeMax']
            if str(check_bool).upper()=="TRUE":
                Dialog.chk_discharge.setChecked(True)
            else:
                Dialog.chk_discharge.setChecked(False)
            check_value=_xmltodict_Project['projectds']['ProjectSettings']['DischargeImgRendererMaxV']
            Dialog.spb_maxRenDischarge.setValue(float(check_value))    
            check_value=_xmltodict_Project['projectds']['ProjectSettings']['OutputPrecision_DischargeMax']
            Dialog.spb_oPrecision_Discharge.setValue(float(check_value)) 

            check_bool=_xmltodict_Project['projectds']['ProjectSettings']['OutputFDofMaxV']
            if str(check_bool).upper()=="TRUE":
                Dialog.chk_direction.setChecked(True)
            else:
                Dialog.chk_direction.setChecked(False)

            #check_bool=_xmltodict_Project['projectds']['ProjectSettings']['OutputRFGrid']
            #if str(check_bool).upper()=="TRUE":
            #    Dialog.chk_Rainfall.setChecked(True)
            #else:
            #    Dialog.chk_Rainfall.setChecked(False)

            #check_value=_xmltodict_Project['projectds']['ProjectSettings']['RFImgRendererMaxV']
            #Dialog.spb_Rainfall.setValue(float(check_value))  

            check_bool=_xmltodict_Project['projectds']['ProjectSettings']['WriteLog']
            if str(check_bool).upper()=="TRUE":
                Dialog.chk_Log.setChecked(True)
            else:
                Dialog.chk_Log.setChecked(False)

            #20181030
            FloodingCellDepthThresholds=_xmltodict_Project['projectds']['ProjectSettings']['FloodingCellDepthThresholds_cm']
            Dialog.txt_Flooding_Threshold.setText(FloodingCellDepthThresholds)

            CellLocationsToPrint=_xmltodict_Project['projectds']['ProjectSettings']['CellLocationsToPrint']
            Dialog.txt_CellLocationsToPrint.setText(CellLocationsToPrint)

            # Change DEM file Group
            Dialog.tbl_DEM_File.setColumnCount(2)
            Dialog.tbl_DEM_File.setColumnWidth(0,90)
            Dialog.tbl_DEM_File.setColumnWidth(1,480)
             
            Dialog.tbl_DEM_File.setHorizontalHeaderLabels(['Time (min)','DEMFile'])

            stylesheet = "::section{Background-color:rgb(225, 225, 225);}"
            Dialog.tbl_DEM_File.horizontalHeader().setStyleSheet(stylesheet)

            if getset.getDEMFileToChange_Count()==0:
                Dialog.tbl_DEM_File.setRowCount(0)
            elif getset.getDEMFileToChange_Count()==1:
                TimeMinute=_xmltodict_Project['projectds']['DEMFileToChange']['TimeMinute']
                DEMFile=_xmltodict_Project['projectds']['DEMFileToChange']['DEMFile']
                Dialog.tbl_DEM_File.insertRow(0)
                #Dialog.tbl_DEM_File.setItem(0, 0, QTableWidgetItem(str(TimeMinute).decode("utf-8")))
                #Dialog.tbl_DEM_File.setItem(0, 1, QTableWidgetItem(str(DEMFile).decode("utf-8")))
                Dialog.tbl_DEM_File.setItem(0, 0, QTableWidgetItem(str(TimeMinute)))
                Dialog.tbl_DEM_File.setItem(0, 1, QTableWidgetItem(str(DEMFile)))
   
            elif getset.getDEMFileToChange_Count()>1:
                i=0
                for item in _xmltodict_Project['projectds']['DEMFileToChange']:
                    Dialog.tbl_DEM_File.insertRow(i)
                    #Dialog.tbl_DEM_File.setItem(i, 0, QTableWidgetItem(str(item['TimeMinute']).decode("utf-8")))
                    #Dialog.tbl_DEM_File.setItem(i, 1, QTableWidgetItem(str(item['DEMFile']).decode("utf-8"))) 

                    Dialog.tbl_DEM_File.setItem(i, 0, QTableWidgetItem(str(item['TimeMinute'])))
                    Dialog.tbl_DEM_File.setItem(i, 1, QTableWidgetItem(str(item['DEMFile'])))
                    i = i +1

            # Rainfall Group
            RainfallDataType=_xmltodict_Project['projectds']['ProjectSettings']['RainfallDataType']
            RainfallDataInterval_min=_xmltodict_Project['projectds']['ProjectSettings']['RainfallDataInterval_min']
            iniRFLoss_mm=_xmltodict_Project['projectds']['ProjectSettings']['InitialRainfallLoss_mm']
            RainfallFile=_xmltodict_Project['projectds']['ProjectSettings']['RainfallFile']
            if RainfallDataType =="TextFileASCgrid":
                Dialog.cmb_Rainfall_Type.setCurrentIndex(2)
            elif RainfallDataType =="TextFileMAP":
                Dialog.cmb_Rainfall_Type.setCurrentIndex(1)
            else:
                Dialog.cmb_Rainfall_Type.setCurrentIndex(0)

            Dialog.spb_Rainfall_Interval.setValue(int(RainfallDataInterval_min))
            Dialog.txt_iniRFLoss_mm.setText(iniRFLoss_mm)
            Dialog.txt_Rainfall_File.setText(RainfallFile)

            # Boundary Group
            value=_xmltodict_Project['projectds']['ProjectSettings']['BCDataInterval_min']
            if str(value)!="None":
                Dialog.txt_min.setValue(int(value))

            combo_box_options = ["Select Type","Discharge","Depth","Height"]
            Dialog.tbl_Boundary.setColumnCount(4)
            Dialog.tbl_Boundary.setColumnWidth(0,110)
            Dialog.tbl_Boundary.setColumnWidth(1,480)
            Dialog.tbl_Boundary.setColumnWidth(2,80)
            Dialog.tbl_Boundary.setColumnWidth(3,400)
            Dialog.tbl_Boundary.setHorizontalHeaderLabels(('Type, Boundary condition file, , Cell position (ex. x1,y1/x2,y2/x3,y3...)').split(', '))
            Dialog.tbl_Boundary.horizontalHeader().setStretchLastSection(True)
 
            
            if getset.getBoundaryConditionData_Count()==0:
                Dialog.tbl_Boundary.setRowCount(0)
                
                for index in range(12):
                    Dialog.tbl_Boundary.insertRow(index)
                    combo = QComboBox()
                    for t in combo_box_options:
                        combo.addItem(t)
                    Dialog.tbl_Boundary.setCellWidget(index,0,combo)
                    item1 = QTableWidgetItem(" ")
                    Dialog.tbl_Boundary.setItem(index,1,item1)
                    btn = QPushButton()
                    btn.setText('...')
                    btn.clicked.connect(self.select_dialog)

                    Dialog.tbl_Boundary.setCellWidget(index,2, btn)
                    Dialog.tbl_Boundary.setItem(index, 1, QTableWidgetItem(" "))
                    Dialog.tbl_Boundary.setItem(index, 3, QTableWidgetItem(" "))

            elif getset.getBoundaryConditionData_Count()==1:
                Dialog.tbl_Boundary.setRowCount(0)
                Dialog.tbl_Boundary.setRowCount(1)
                CellXY=""
                # 2018-02-20 박: 기능 변경으로 소스 수정
                CellXY=_xmltodict_Project['projectds']['BoundaryConditionData']['CellXY'] 
                combo = QComboBox()
                #테이블 내 콥보박스 셋팅
                for t in combo_box_options:
                    combo.addItem(t)
                    
                if str(_xmltodict_Project['projectds']['BoundaryConditionData']['DataType']).upper()=="DISCHARGE":
                    combo.setCurrentIndex(1)
                elif str(_xmltodict_Project['projectds']['BoundaryConditionData']['DataType']).upper()=="DEPTH":
                    combo.setCurrentIndex(2)
                elif str(_xmltodict_Project['projectds']['BoundaryConditionData']['DataType']).upper()=="HEIGHT":
                    combo.setCurrentIndex(3)
                else:
                    combo.setCurrentIndex(0)

                Dialog.tbl_Boundary.setCellWidget(0, 0, combo)
                Dialog.tbl_Boundary.setItem(0, 1, QTableWidgetItem(str(_xmltodict_Project['projectds']['BoundaryConditionData']['DataFile'])))

                btn = QPushButton()
                btn.setText('...')
                btn.clicked.connect(self.select_dialog)
                Dialog.tbl_Boundary.setCellWidget(0, 2, btn)
                #Dialog.tbl_Boundary.setItem(0, 3, QTableWidgetItem(str(CellXY).decode("utf-8")))
                Dialog.tbl_Boundary.setItem(0, 3, QTableWidgetItem(str(CellXY)))

            elif getset.getBoundaryConditionData_Count()>1:
                Dialog.tbl_Boundary.setRowCount(0)
                j=0
                for item in _xmltodict_Project['projectds']['BoundaryConditionData']:
                    Dialog.tbl_Boundary.insertRow(j)
                    CellXY=str(item['CellXY']) 

                    # 2019-05-22 박: 임시 주석 
                    combo = QComboBox()
                    for t in combo_box_options:
                            combo.addItem(t)
                    if str(item['DataType']).upper()=="DISCHARGE":
                        combo.setCurrentIndex(1)
                    elif str(item['DataType']).upper()=="DEPTH":
                        combo.setCurrentIndex(2)
                    elif str(item['DataType']).upper()=="HEIGHT":
                        combo.setCurrentIndex(3)
                    else:
                        combo.setCurrentIndex(0)

                    Dialog.tbl_Boundary.setCellWidget(j, 0, combo)
                    Dialog.tbl_Boundary.setItem(j, 1, QTableWidgetItem(str(item['DataFile'])))
                    btn = QPushButton()
                    btn.setText('...')
                    btn.clicked.connect(self.select_dialog)
                    Dialog.tbl_Boundary.setCellWidget(j, 2, btn)
                    Dialog.tbl_Boundary.setItem(j, 3, QTableWidgetItem(CellXY))
                    j = j +1

        except Exception as e:
            MsError(e)
            
    def test111(self):
        MsInfo("ddd")

    def Set_LandCover_Enable_Option(self):
        if Dialog.rdo_Land_Cover.isChecked():
            Dialog.rdo_Constant_Value.setChecked(False)
            Dialog.txt_landcover.setDisabled(False)
            Dialog.txt_lcVat.setDisabled(False)
            Dialog.btn_Land_Dialog.setDisabled(False)
            Dialog.btn_LC_Dialog.setDisabled(False)
            Dialog.txt_roughness.setDisabled(True)
            #Dialog.txt_impervious.setDisabled(True)
        else: 
            Dialog.rdo_Constant_Value.setChecked(True)
            Dialog.txt_landcover.setDisabled(True)
            Dialog.txt_lcVat.setDisabled(True)
            Dialog.btn_Land_Dialog.setDisabled(True)
            Dialog.btn_LC_Dialog.setDisabled(True)
            
            Dialog.txt_roughness.setDisabled(False)
            #Dialog.txt_impervious.setDisabled(False)


    def select_dialog(self):
        try:
            File_Path = QFileDialog.getOpenFileName(QFileDialog(), "G2D", "", "*.*")[0]
            button = Dialog.sender()
            index = Dialog.tbl_Boundary.indexAt(button.pos())
            if index.isValid():
                Dialog.tbl_Boundary.setItem(index.row(), 1, QTableWidgetItem(File_Path))
        except Exception as e:
            MsError(e)

    def Set_GPU(self):
        if Dialog.chk_Using_GPU.isChecked():
            Dialog.spb_GPU_ThreadsPerBlock.setDisabled(False)
            #Dialog.spb_GPU_GS.setDisabled(False)
            #Dialog.spb_GPU_NR.setDisabled(False)
            #Dialog.spb_GPU_Threshold.setDisabled(False)
        else:
            Dialog.spb_GPU_ThreadsPerBlock.setDisabled(True)
            #Dialog.spb_GPU_GS.setDisabled(True)
            #Dialog.spb_GPU_NR.setDisabled(True)
            #Dialog.spb_GPU_Threshold.setDisabled(True)


    def Set_Starting_time(self):
        if Dialog.chk_Starting_time.isChecked():
            Dialog.dte_Starting_time.setDisabled(False)
            Dialog.spb_Starting_time.setDisabled(True)
        else:
            Dialog.dte_Starting_time.setDisabled(True)
            Dialog.spb_Starting_time.setDisabled(False)


    def Save_ProjectXML(self,profile):
        try:
            if len(_xmltodict_Project)>0:
                # Domain Group 
                _xmltodict_Project['projectds']['ProjectSettings']['DEMFile'] = Dialog.txt_dem.text()
                #_xmltodict_Project['projectds']['ProjectSettings']['DomainFile'] = Dialog.txt_domain.text()

                #Land Cover Group
                _xmltodict_Project['projectds']['ProjectSettings']['LandCoverFile'] =Dialog.txt_landcover.text()
                _xmltodict_Project['projectds']['ProjectSettings']['LandCoverVatFile'] = Dialog.txt_lcVat.text()
                _xmltodict_Project['projectds']['HydroPars']['RoughnessCoeff']=Dialog.txt_roughness.text()
                #_xmltodict_Project['projectds']['HydroPars']['ImperviousRatio']=Dialog.txt_impervious.text()

                #Hydraulic parameters  Group
                #2019-20-20 박: InitialDepth 삭제  InitialConditionType,InitialCondition 추가
                #_xmltodict_Project['projectds']['HydroPars']['InitialDepth'] = Dialog.txt_initwd.text()
                _xmltodict_Project['projectds']['HydroPars']['InitialConditionType'] = Dialog.cmb_ConditionType.currentText()
                _xmltodict_Project['projectds']['HydroPars']['InitialCondition'] = Dialog.txt_conditon_File.text()

                _xmltodict_Project['projectds']['HydroPars']['FroudeNumberCriteria'] = Dialog.txt_Froud.text()
                _xmltodict_Project['projectds']['HydroPars']['CourantNumber'] = Dialog.txt_courant.text()
                _xmltodict_Project['projectds']['HydroPars']['DomainOutBedSlope']=Dialog.txt_slope.text()


                if Dialog.chk_Apply_VNC.isChecked():
                    _xmltodict_Project['projectds']['HydroPars']['ApplyVNC'] = "true"
                else:
                    _xmltodict_Project['projectds']['HydroPars']['ApplyVNC'] = "false"

                 #Simulation settings Group
                if Dialog.chk_FixedDT.isChecked():
                    _xmltodict_Project['projectds']['ProjectSettings']['IsFixedDT']= "true"
                else:
                    _xmltodict_Project['projectds']['ProjectSettings']['IsFixedDT']= "false"

                _xmltodict_Project['projectds']['ProjectSettings']['CalculationTimeInterval_sec'] = str(Dialog.spb_Starting_Cal_time.value())

                #if Dialog.chk_Parallel.isChecked():
                #   _xmltodict_Project['projectds']['ProjectSettings']['IsParallel']="true"
                #else:
                #    _xmltodict_Project['projectds']['ProjectSettings']['IsParallel']="false"
                _xmltodict_Project['projectds']['ProjectSettings']['MaxDegreeOfParallelismCPU'] = str(Dialog.spb_Parallel_value.value())
                if Dialog.chk_Using_GPU.isChecked():
                    _xmltodict_Project['projectds']['ProjectSettings']['UsingGPU']="true"
                    _xmltodict_Project['projectds']['ProjectSettings']['ThreadsPerBlock'] = str(Dialog.spb_GPU_ThreadsPerBlock.value())
                else:
                    _xmltodict_Project['projectds']['ProjectSettings']['UsingGPU']="false"
                    _xmltodict_Project['projectds']['ProjectSettings']['ThreadsPerBlock'] = ''

                #_xmltodict_Project['projectds']['ProjectSettings']['EffCellThresholdForGPU'] = str(Dialog.spb_GPU_Threshold.value())
                _xmltodict_Project['projectds']['ProjectSettings']['MaxIterationAllCells'] = str(Dialog.spb_CPU_GS.value())
                _xmltodict_Project['projectds']['ProjectSettings']['MaxIterationACell'] = str(Dialog.spb_CPU_NR.value())
                #_xmltodict_Project['projectds']['ProjectSettings']['MaxIterationAllCellsOnGPU'] = str(Dialog.spb_GPU_GS.value())
                #_xmltodict_Project['projectds']['ProjectSettings']['MaxIterationACellOnGPU'] = str(Dialog.spb_GPU_NR.value())                

                if Dialog.chk_Starting_time.isChecked():
                    dt = Dialog.dte_Starting_time.dateTime()
                    date_time=dt.toString("yyyy-MM-dd hh:mm")
                    #_xmltodict_Project['projectds']['ProjectSettings']['StartDateTime']=Dialog.dte_Starting_time.dateTime()
                    _xmltodict_Project['projectds']['ProjectSettings']['StartDateTime']=date_time
                else:
                    _xmltodict_Project['projectds']['ProjectSettings']['StartDateTime']="0"

                _xmltodict_Project['projectds']['ProjectSettings']['SimulationDuration_hr']=str(Dialog.spb_Simulation_Hour.value())

                # Output options Group
                _xmltodict_Project['projectds']['ProjectSettings']['PrintoutInterval_min'] = str(Dialog.spb_Output_Step.value())
            
                if Dialog.chk_makeASCII.isChecked():
                    _xmltodict_Project['projectds']['ProjectSettings']['MakeASCFile'] = "true"
                else:
                    _xmltodict_Project['projectds']['ProjectSettings']['MakeASCFile'] = "false"

                if Dialog.chk_makeimg.isChecked():
                    _xmltodict_Project['projectds']['ProjectSettings']['MakeImgFile'] = "true"
                else:
                    _xmltodict_Project['projectds']['ProjectSettings']['MakeImgFile'] = "false"

                if Dialog.chk_wdepth.isChecked():
                    _xmltodict_Project['projectds']['ProjectSettings']['OutputDepth'] = "true"
                else:
                    _xmltodict_Project['projectds']['ProjectSettings']['OutputDepth'] = "false"

                _xmltodict_Project['projectds']['ProjectSettings']['DepthImgRendererMaxV'] = str(Dialog.spb_maxRenDepth.value())  
                _xmltodict_Project['projectds']['ProjectSettings']['OutputPrecision_Depth'] = str(Dialog.spb_oPrecision_Depth.value())  

                if Dialog.chk_waterLevel.isChecked():
                    _xmltodict_Project['projectds']['ProjectSettings']['OutputWaterLevel']="true"
                else:
                    _xmltodict_Project['projectds']['ProjectSettings']['OutputWaterLevel']="false"

                _xmltodict_Project['projectds']['ProjectSettings']['WaterLevelimgRendererMaxV']=str(Dialog.spb_maxRenLevel.value()) 
                _xmltodict_Project['projectds']['ProjectSettings']['OutputPrecision_WaterLevel'] = str(Dialog.spb_oPrecision_WaterLevel.value())  

                if Dialog.chk_velocity.isChecked():
                    _xmltodict_Project['projectds']['ProjectSettings']['OutputVelocityMax']="true"
                else:
                    _xmltodict_Project['projectds']['ProjectSettings']['OutputVelocityMax']="false"

                _xmltodict_Project['projectds']['ProjectSettings']['VelocityMaxImgRendererMaxV'] = str(Dialog.spb_maxRenVelocity.value())  
                _xmltodict_Project['projectds']['ProjectSettings']['OutputPrecision_VelocityMax'] = str(Dialog.spb_oPrecision_Velocity.value())  

                if Dialog.chk_discharge.isChecked():
                    _xmltodict_Project['projectds']['ProjectSettings']['OutputDischargeMax'] = "true"
                else:
                    _xmltodict_Project['projectds']['ProjectSettings']['OutputDischargeMax'] = "false"

                _xmltodict_Project['projectds']['ProjectSettings']['DischargeImgRendererMaxV'] = str(Dialog.spb_maxRenDischarge.value())   
                _xmltodict_Project['projectds']['ProjectSettings']['OutputPrecision_DischargeMax'] = str(Dialog.spb_oPrecision_Discharge.value())  

                if Dialog.chk_direction.isChecked():
                    _xmltodict_Project['projectds']['ProjectSettings']['OutputFDofMaxV']="true"
                else:
                    _xmltodict_Project['projectds']['ProjectSettings']['OutputFDofMaxV']="false"

                #if Dialog.chk_Rainfall.isChecked():
                #    _xmltodict_Project['projectds']['ProjectSettings']['OutputRFGrid'] = "true"
                #else:
                #    _xmltodict_Project['projectds']['ProjectSettings']['OutputRFGrid'] = "false"

                #_xmltodict_Project['projectds']['ProjectSettings']['RFImgRendererMaxV']=str(Dialog.spb_Rainfall.value())  

                if Dialog.chk_Log.isChecked():
                    _xmltodict_Project['projectds']['ProjectSettings']['WriteLog']="true"
                else:
                    _xmltodict_Project['projectds']['ProjectSettings']['WriteLog']="false"

                _xmltodict_Project['projectds']['ProjectSettings']['FloodingCellDepthThresholds_cm']=Dialog.txt_Flooding_Threshold.text()
                _xmltodict_Project['projectds']['ProjectSettings']['CellLocationsToPrint']=Dialog.txt_CellLocationsToPrint.text()

                # Change DEM file Group
                if getset.getDEMFileToChange_Count() > 0:
                    del _xmltodict_Project['projectds']['DEMFileToChange']
                #DictoXml = xmltodict.unparse(_xmltodict_Project)
                DictoXml = unparse(_xmltodict_Project)
                ET.register_namespace('', "http://tempuri.org/projectds.xsd")
                xmltree = ET.ElementTree(ET.fromstring(DictoXml))
                root = xmltree.getroot()
                
                #2019-08-08 박: 테이블 내용 오류로 추가 사항
                getset.setDEMFileToChange_Count(Dialog.tbl_DEM_File.rowCount())
                for row in range(0, Dialog.tbl_DEM_File.rowCount()):
                    child = ET.Element("DEMFileToChange")
                    root.append(child)

                    TimeMinute = ET.Element("TimeMinute")
                    TimeMinute.text = Dialog.tbl_DEM_File.item(row, 0).text()
                    child.append(TimeMinute)

                    DEMFile = ET.Element("DEMFile")
                    DEMFile.text = Dialog.tbl_DEM_File.item(row, 1).text()
                    #2019-12-11 박: 없어서 추가
                    child.append(DEMFile)

                xmltree_string = ET.tostring(xmltree.getroot())
                docs = dict(parse(xmltree_string))
                #docs = dict(xmltodict.parse(xmltree_string))
                _xmltodict_Project.clear()
                _xmltodict_Project.update(docs)
            
                # Rainfall Group
                _xmltodict_Project['projectds']['ProjectSettings']['RainfallDataType'] =Dialog.cmb_Rainfall_Type.currentText()
                _xmltodict_Project['projectds']['ProjectSettings']['RainfallDataInterval_min'] = str(Dialog.spb_Rainfall_Interval.value())  
                _xmltodict_Project['projectds']['ProjectSettings']['RainfallFile'] = Dialog.txt_Rainfall_File.text()


                # Boundery Group
                _xmltodict_Project['projectds']['ProjectSettings']['BCDataInterval_min']= str(Dialog.txt_min.value())

               
                if getset.getBoundaryConditionData_Count() > 0:
                    del _xmltodict_Project['projectds']['BoundaryConditionData']
                #DictoXml = xmltodict.unparse(_xmltodict_Project)
                DictoXml = unparse(_xmltodict_Project)
                ET.register_namespace('', "http://tempuri.org/projectds.xsd")
                xmltree = ET.ElementTree(ET.fromstring(DictoXml))
                root = xmltree.getroot()
                
                getset.setBoundaryConditionData_Count(Dialog.tbl_Boundary.rowCount())
                for row in range(0, Dialog.tbl_Boundary.rowCount()):
                    
                    CellXY = Dialog.tbl_Boundary.item(row, 3).text()
                    #QMessageBox.information(None, "CellXY", str(CellXY))
                    if CellXY=="":
                        continue

                    DataFile = Dialog.tbl_Boundary.item(row, 1).text()
                    if DataFile =="":
                        continue

                    widget = Dialog.tbl_Boundary.cellWidget(row, 0)
                    current_value = widget.currentText()
                    if current_value =="Select Type":
                        continue

                    child = ET.Element("BoundaryConditionData")
                    root.append(child)

                    
                    # 2018-02-20 박: 기존 기능 변경으로 인한 수정 
                    CellXYs = ET.Element("CellXY")
                    CellXYs.text = Dialog.tbl_Boundary.item(row,3).text()
                    child.append(CellXYs)

                    #CellXY = Dialog.tbl_Boundary.item(row, 3).text()
                    #Boundry_Data = CellXY.split('/')
                    #testa=[]
                    #for i in range(len(Boundry_Data)):
                        #testa.append("CellXY"+str(i+1))
                        #testa[i]=ET.Element(testa[i])
                        #testa[i].text=Boundry_Data[i]
                        #child.append(testa[i])


                    DataFile = ET.Element("DataFile")
                    DataFile.text = Dialog.tbl_Boundary.item(row, 1).text()
                    child.append(DataFile)

                    DEMFile = ET.Element("DataType")
                    DEMFile.text = current_value
                    child.append(DEMFile)

                xmltree_string = ET.tostring(xmltree.getroot())
                docs = dict(parse(xmltree_string))
                _xmltodict_Project.clear()
                _xmltodict_Project.update(docs)

                #DictoXml = xmltodict.unparse(_xmltodict_Project)
                DictoXml = unparse(_xmltodict_Project)
                fw = open(profile, 'w+')
                fw.write(DictoXml)
                fw.close()                
                
                self.indent(profile)
                

        except Exception as e:
            MsError(e)
            return


    def Check_SaveData(self):
        try:
            if len(_xmltodict_Project) > 0:
                if (self.Txt_Error_Message(Dialog.txt_dem,"DEM file is not entered."))==False:
                    return False
                if Dialog.rdo_Land_Cover.isChecked():
                    if (self.Txt_Error_Message(Dialog.txt_landcover," Land cover file is not entered."))==False:
                        return False
                    if (self.Txt_Error_Message(Dialog.txt_lcVat," Land cover VAT file is not entered."))==False:
                        return False

                if Dialog.rdo_Constant_Value.isChecked():
                    if (self.Txt_Error_Message(Dialog.txt_roughness," RoughnessCoeff coeff. value is not entered."))==False:
                        return False
                    #if (self.Txt_Error_Message(Dialog.txt_impervious," Impervious ratio value is not entered."))==False:
                    #    return
                # 2019-02-20 박: txt_initwd 삭제
                #if (self.Txt_Error_Message(Dialog.txt_initwd," Initial water depth value is not entered."))==False:
                #        return
                if Dialog.cmb_ConditionType.currentIndex()==0:
                    QMessageBox.information(None, "G2D", "Select conditon type")
                    Dialog.cmb_ConditionType.setFocus()
                    return False

                if (self.Txt_Error_Message(Dialog.txt_conditon_File," Condition value is not entered."))==False:
                    Dialog.txt_conditon_File.setFocus()
                    return False

                condition = Dialog.txt_conditon_File.text()
                if self.CheckFile(condition) or self.is_number(condition):
                    pass
                else:
                    QMessageBox.information(None, "G2D", " Condition value is invalid.")
                    Dialog.txt_conditon_File.setFocus()
                    return False


                if (self.Txt_Error_Message(Dialog.txt_courant," Courant N. criteria value is not entered."))==False:
                    return False
                if (self.Txt_Error_Message(Dialog.txt_Froud," Froud N. criteria value is not entered."))==False:
                    return False
                if (self.Txt_Error_Message(Dialog.txt_slope," Bed slope to domain out value is not entered."))==False:
                    return False

                if (self.Spb_Error_Message(Dialog.spb_Simulation_Hour," Simulation duration value is not entered.",0))==False:
                    return False
        
                if Dialog.cmb_Rainfall_Type.currentIndex()==0:
                    QMessageBox.information(None, "G2D", "select Rainfall type")
                    #control.cmb_Rainfall_Type
                    return False
                rowcount = Dialog.tbl_Boundary.rowCount()
                print("table xy : ",str(rowcount) )
                #2019/11/18 박: 데이터 모두 초기화 오류 
                if rowcount>0:
                    #2019-12-11 박: 추가
                    for row in reversed(range(rowcount)):
                        current_value = Dialog.tbl_Boundary.cellWidget(row,0).currentText()
                        DataFile = Dialog.tbl_Boundary.item(row, 1).text()
                        CellXY = Dialog.tbl_Boundary.item(row, 3).text()
                        print("table xy : ", Dialog.tbl_Boundary.item(row, 3).text())
                        Dialog.tbl_Boundary.setFocus()
                        if CellXY==" " or DataFile ==" " or current_value =="Select Type":
                            print("table xy : ", Dialog.tbl_Boundary.item(row, 3).text())
                            Dialog.tbl_Boundary.removeRow(row)
                return True

            else:
                return False
        except Exception as e:
            MsError(e)
    def Txt_Error_Message(self,control,message):
        if control.text()=="":
            MsError(message)
            control.setFocus()
            return False
        else:
            return True

    def Spb_Error_Message(self,control,message,errorvalue):
        if control.value()==int(errorvalue):
            MsInfo(message)
            control.setFocus()
            return False
        else:
            return True

    # 파일 존재 유무 확인
    def CheckFile(self, path):
        filepath = path.replace('\\', '\\\\')
        if (os.path.isfile(filepath)):
            return True
        else:
            return False

    # 숫자가 맞는지 확인
    def is_number(self,num):
        try:
            judge = str(float(num))
            return False if(judge=='nan' or judge=='inf' or judge =='-inf') else True
        except(ValueError, type): #num을 float으로 변환 할 수 없는 경우
            return False

    def indent(self,Pro_path):
        arg=GetScriptDirectory_Path()+ "/ReWriteXML/ReadAndWriteXML.exe " + Pro_path
        callExecute(arg)