# -*- coding: utf-8 -*-
"""
/***************************************************************************
 G2DDialog
                                 A QGIS plugin
  
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2019-05-13
        git sha              : $Format:%H$
        copyright            : (C) 2019 by KICT, 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 subprocess
import time
from PyQt5 import uic, QtTest
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QDockWidget

# Dockwidget 스타일 적용
from .css import *
from .lib.Util import *
from .XMLCheck import xmls
from .Set_Value_Control import *
from .xmltodict import *
from .G2D_Ini import *
from .XMLMake import *
from .Canvas_dialog import *
import threading
from .Make_PRJ_dialog import *
from .Settings_dialog import *
from .about_dialog import *
_Make_Xml= Make()
_xmltodict={}
G2DIni = G2Dini()


# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'g2d_dialog_base.ui'))

class G2DDialog(QtWidgets.QMainWindow, FORM_CLASS):
    _dem_path = ""
    def __init__(self, parent=None):
        super(G2DDialog, self).__init__(parent)
        self.setupUi(self)
        self.setDockWidget()
        self.ini_Qmenubar()
        self.setDockWidget_Enable(False)
        self.setini()
        self.setLandcover_control()
        
    # DOCKWidget 초기 셋팅    
    def setDockWidget(self):
        self.setStyleSheet(css_sheet)
        self.dockList = [self.doc_domain,
                self.doc_landCover,self.doc_hydraulic,
                self.doc_simulation,self.doc_changeDEM,
                self.doc_boundary,self.doc_rainfall,
                self.doc_output, self.doc_controller]
        for dock in self.dockList:
            dock.setFeatures(QDockWidget.NoDockWidgetFeatures)

    def setLandcover_control(self):
        self.Land_Cover_List = [self.txt_landcover,self.btn_Land_Dialog,self.txt_lcVat,self.btn_LC_Dialog]
        self.Land_Const_List = [self.txt_roughness]
        #self.SimulSetList= [self.spb_GPU_GS,self.spb_GPU_NR,self.spb_GPU_Threshold]
        self.SimulSetList= [self.spb_GPU_ThreadsPerBlock]
    # DOCKWidget 초기 셋팅    
    def setDockWidget_Enable(self,flag):
        for dock in self.dockList:
            dock.setEnabled(flag)

    def setini(self):
        try:
            self.current_timer = None
            self.current_timer = QTimer()
            self.Add_Menu_Flag= False
            self.project_Controls = Set_ProjectToControls(self)

            # 콤보 박스 배열 받아서 셋팅 하기
            self.cmb_ConditionType.addItems(G2DIni.Condition_combo)
            self.cmb_Rainfall_Type.addItems(G2DIni.Rainfall_Type)

            # 다이얼 로그 이벤트 
            self.btn_DEM_dialog.clicked.connect(lambda: self.FileDialog("*.*",self.txt_dem))
            self.btn_Land_Dialog.clicked.connect(lambda: self.FileDialog("*.*",self.txt_landcover))
            self.btn_LC_Dialog.clicked.connect(lambda: self.FileDialog("*.*",self.txt_lcVat))
            self.btn_condition_file.clicked.connect(lambda: self.FileDialog("*.ASC",self.txt_conditon_File))
            self.btn_Dem_file.clicked.connect(lambda: self.FileDialog("*.*",self.txt_Cange_dem_File))
            self.btn_Rainfall_Dialog.clicked.connect(lambda: self.FileDialog("*.*",self.txt_Rainfall_File))


            # 라디오 박스 이벤트 
            self.rdo_Land_Cover.clicked.connect(self.Land_RdoEvent)
            self.rdo_Constant_Value.clicked.connect(self.Land_RdoEvent)

            #체크 박스 이벤트
            self.chk_Using_GPU.stateChanged.connect(self.SimuOption)
            self.chk_Starting_time.stateChanged.connect(self.SimuOption)

            self.chk_wdepth.stateChanged.connect(lambda:self.ChangeState_Output_options(self.chk_wdepth,self.spb_maxRenDepth, self.spb_oPrecision_Depth))
            self.chk_waterLevel.stateChanged.connect(lambda:self.ChangeState_Output_options(self.chk_waterLevel,self.spb_maxRenLevel, self.spb_oPrecision_WaterLevel))
            self.chk_velocity.stateChanged.connect(lambda:self.ChangeState_Output_options(self.chk_velocity,self.spb_maxRenVelocity, self.spb_oPrecision_Velocity))
            self.chk_discharge.stateChanged.connect(lambda:self.ChangeState_Output_options(self.chk_discharge,self.spb_maxRenDischarge, self.spb_oPrecision_Discharge))
            #self.chk_Rainfall.stateChanged.connect(lambda:self.Check_chk_Output_image(self.chk_Rainfall,self.spb_Rainfall))


            self.chk_makeimg.stateChanged.connect(self.Set_makeimg)
            self.chk_makeASCII.stateChanged.connect(self.Set_makeimg)

            # DEM file Table 
            self.btn_Change_DEM_Apply.clicked.connect(self.Chagne_DEM_Apply)
            self.btn_Change_DEM_Delete.clicked.connect(lambda:self.Delete_Table_Data(self.tbl_DEM_File))

            # Boundary table
            self.btn_Boundary_Add.clicked.connect(self.Add_Row_Boundary)
            self.btn_Boundary_Delete.clicked.connect(lambda:self.Delete_Table_Data(self.tbl_Boundary))

            #2019-02-25 박: 종료 버튼 이벤트 추가 
            self.btn_close.clicked.connect(self.Close_Form)
            
            # 시뮬레이션 이벤트
            self.btn_simulation.clicked.connect(self.Simulation)
            # 시뮬레이션 결과            
            self.btn_show_simulation_Result.clicked.connect(self.Show_simulation_result)

        except Exception as e:
            MsError(e)

    def ini_Qmenubar(self):
        try:
            #New Project 이벤트
            New_Project = QAction('New Project', self)
            New_Project.triggered.connect(self.New)

            #Open Project 이벤트
            Open_Project = QAction('Open Project', self)
            Open_Project.triggered.connect(self.Open)
            
            mainMenu = self.menuBar()
            self.Project_Menu = mainMenu.addMenu('&Project  ')
            self.Project_Menu.addAction(New_Project)
            self.Project_Menu.addAction(Open_Project)

            #환경 설정
            Settings_setting = QAction('QML Settings', self)
            Settings_setting.triggered.connect(self.OpenSettings)

            #About 창
            Settings_info = QAction('QGIS-G2D info', self)
            Settings_info.triggered.connect(self.AboutOpen)

            self.Settings_Menu = mainMenu.addMenu('&Settings ')
            self.Settings_Menu.addAction(Settings_setting)
            self.Settings_Menu.addAction(Settings_info)

        except Exception as e:
            MsError(e)

    def OpenSettings(self):
        canvas=SettingsDialog(None)
        canvas.exec_()


    def AboutOpen(self):
        canvas=AboutDialog(None)
        canvas.exec_()

    # project file open
    def Open(self):
        try:
            self.Clear_Table()

            # 파일 경로를 초기화 하고 프로젝트 파일 받음
            G2DIni.Proj_File=""
            G2DIni.Proj_File=OpenFileDialog("*.g2p")
            if G2DIni.Proj_File!="":
                if ChFile_Exists(G2DIni.Proj_File):
                    self.Convert_ProjectXML_Dict()
                    if self.Add_Menu_Flag==False:                
                        self.Add_Menu()
                        self.Add_Menu_Flag = True
                    self.setDockWidget_Enable(True)
                    self.set_tbl_Boundary()
                    self.txt_Cange_dem_File.setText("")
            else:
                MsIn('Open project failed') 
            self.project_Controls.Save_ProjectXML(G2DIni.Proj_File)


        except NameError:
            MsError('Open project failed') 

    def Convert_ProjectXML_Dict(self):
        global _xmltodict
        try:

            result = self.project_Controls.Check_Project_file(G2DIni.Proj_File)
            _xmltodict = result
        except Exception as e:
            MsError(e)

    def New(self):
        try:
            # 파일 경로가 정상인지 체크하는 부분이 없음 함수 추가 해야함 

            self.Clear_Table()
            #New프로젝트 파일 생성 경로 받아 오기
            G2DIni.Proj_File=""
            G2DIni.Proj_File=saveFileDialog("*.g2p")
            
            #XML파일 생성
            if G2DIni.Proj_File!="":
                _Make_Xml.Make_G2P_File(G2DIni.Proj_File)
                if ChFile_Exists(G2DIni.Proj_File):
                    #생성된 XML파일로 컨트롤러 셋팅
                    self.project_Controls.Check_Project_file(G2DIni.Proj_File)
                    self.setDockWidget_Enable(True)
                    if self.Add_Menu_Flag==False:                
                        self.Add_Menu()
                        self.Add_Menu_Flag = True

                    #2019/11/18 박: 최박사님 수정사항
                    combo_box_options = ["Select Type","Discharge","Depth","Height"]
                    #combo_box_options = ["Select Type","Discharge","Depth"]
                    self.tbl_Boundary.setRowCount(0)
                    self.txt_Cange_dem_File.setText("")
                    for index in range(12):
                        self.tbl_Boundary.insertRow(index)
                        combo = QComboBox()
                        for t in combo_box_options:
                            combo.addItem(t)
                        self.tbl_Boundary.setCellWidget(index,0,combo)
                        item1 = QTableWidgetItem(" ")
                        self.tbl_Boundary.setItem(index,1,item1)
                        btn = QPushButton()
                        btn.setText('...')
                        btn.clicked.connect(self.select_dialog)

                        self.tbl_Boundary.setCellWidget(index,2, btn)
                        self.tbl_Boundary.setItem(index, 1, QTableWidgetItem(" "))
                        self.tbl_Boundary.setItem(index, 3, QTableWidgetItem(" "))
            else:
                MsInfo(" The project file was not created. ")
        except NameError:
            MsError('New project failed') 

    # New, Open 성공시 Save as , Save 목록 추가 
    def Add_Menu(self):
        
        #Save Project 이벤트
        Save_Project = QAction('Save Project', self)
        Save_Project.triggered.connect(lambda: self.SaveProject("save"))

        #Save As Project 이벤트
        Save_As_Project = QAction('Save As Project', self)
        Save_As_Project.triggered.connect(self.SaveasProject)
        
        self.Project_Menu.addAction(Save_Project)
        self.Project_Menu.addAction(Save_As_Project)

    def Simulation(self):
        try:
            # 프로젝트 파일 저장
            self.SaveProject("Simulation")
            time.sleep(0.5)
            #2019-09-20 박: DEM 파일에 PRJ가 없으면 실행 중단함 
            s = os.path.splitext(self.txt_dem.text())[0]+".prj"
            self.thread = []
            if ChFile_Exists(s):
                #쓰레드 분리해서 실행 

                if self.chk_simul_result.isChecked():
                    #2019-10-22 박: QML 파일 지우기 기능 추가
                    self.deleteQML()
                    self.my_thread = threading.Thread(target=self.execute_G2D)
                    self.thread.append(self.my_thread)
                    self.my_thread.start()
                    QtTest.QTest.qWait(1000)
                    canvas=CanvasDialog(None,self.txt_dem.text(),G2DIni.Proj_File,"YES", self.thread)
                    canvas.exec_()
                    self.my_thread.join()
                else:
                    #2019-10-22 박: QML 파일 지우기 기능 추가 
                    self.deleteQML()
                    self.btn_show_simulation_Result.setEnabled(False)
                    self.btn_simulation.setEnabled(False)
                    self.btn_close.setEnabled(False)
                    self.current_timer.timeout.connect(lambda:self.CheckThread(self.thread))
                    self.my_thread = threading.Thread(target=self.execute_G2D)
                    self.thread.append(self.my_thread)
                    self.my_thread.start()
                    self.my_thread.join()
                    self.current_timer.start(2000)
            else: 
                #DEM 에 PRJ 좌표계 파일이 없으면 프로세스 실행 하지 않고 PRJ 생성 창 오픈
                #2019-09-23 박: 최박사님과 업무협의로 기능 변경 PRJ 파일 없으면 기능 실행 안함
                MsInfo("PRJ files are required for DEM files.")
        except Exception as e:
            MsError(e)

    def deleteQML(self):
        try:
            Folder_Files=[]
            Folder_Path=GetFileDirectory_Path(G2DIni.Proj_File)
            Folder_Files = sorted(glob.glob(os.path.join(Folder_Path, '*.qml')), key=os.path.getctime)
            for fname in Folder_Files:
                pass
            j =0
            for c in Folder_Files:
                os.remove(c)

        except Exception as e:
            MsError(e)

    def CheckThread(self,th):
        if not th[0].is_alive():
            self.current_timer.stop()
            self.btn_show_simulation_Result.setEnabled(True)
            self.btn_simulation.setEnabled(True)
            self.btn_close.setEnabled(True)


    #2019-09-23 박: 최박사님과 업무협의로 기능 변경 PRJ 파일 없으면 기능 실행 안함
    #def showdialog(self):
    #    try:
    #        msg = QMessageBox()
    #        msg.setIcon(QMessageBox.Information)
    #        msg.setText("PRJ file does not exist")
    #        msg.setInformativeText("PRJ files are required for DEM files.")
    #        msg.setWindowTitle("G2D")
    #        #msg.setDetailedText("The PRJ file in the DEM file is required to set the coordinate information in the OUT file.")
    #        msg.setStandardButtons(QMessageBox.Ok)
    #        #msg.buttonClicked.connect(test)
    #        retval = msg.exec_()
    #        if retval == QMessageBox.Ok:
    #            canvas=MAKE_PRJ(None)
    #            canvas.exec_()
    #    except Exception as e:
    #        MsError(e)

    def execute_G2D(self):
        try:
            #G2DCore_exe = os.path.dirname(os.path.realpath(__file__)) + "\G2D\G2D.exe"
            #arg = f'"{G2DCore_exe}" {G2DIni.Proj_File}"'
            fpn_g2d = os.path.dirname(os.path.realpath(__file__)) + "//G2D//g2d.exe"
            if ChFile_Exists(fpn_g2d):
                arg = fpn_g2d+ " "+'"' + G2DIni.Proj_File + '"'
                Execute(arg)                
            else:
                MsError(" " + fpn_g2d + " is invalid !!!")
        except Exception as e:
            MsError(e)

    # 프로젝트 파일 저장
    def SaveProject(self,type):
        try: 
            Check_Result=self.project_Controls.Check_SaveData()
            if Check_Result:
                self.project_Controls.Save_ProjectXML(G2DIni.Proj_File)
                if type!="Simulation":
                    MsInfo(G2DIni.Proj_File+" was saved. ")
        except Exception as e:
            MsError("Saving project file was failed !!!")

    # 프로젝트 파일 저장
    def SaveasProject(self):
        File_Path = QFileDialog.getSaveFileName(QFileDialog(), "Save as project", os.getcwd(), "*.g2p")
        if File_Path:
            G2DIni.Proj_File=File_Path[0]
            Check_Result=self.project_Controls.Check_SaveData()
            if Check_Result:
                self.project_Controls.Save_ProjectXML(G2DIni.Proj_File)
                MsInfo(" " +G2DIni.Proj_File+" was saved. ")
        else:
            MsInfo(" Saving project file was failed !!!")


    def FileDialog(self,type,txt):
        txt.setText('')
        filpath=OpenFileDialog(type)
        txt.setText(filpath)

    def Land_RdoEvent(self):
        for control in self.Land_Cover_List:
            control.setEnabled(self.rdo_Land_Cover.isChecked())
        self.txt_roughness.setEnabled(not self.rdo_Land_Cover.isChecked())

    def SimuOption(self):
        for control in self.SimulSetList:
            control.setDisabled(not self.chk_Using_GPU.isChecked())
        self.dte_Starting_time.setDisabled(not self.chk_Starting_time.isChecked())
        self.spb_Starting_time.setDisabled(self.chk_Starting_time.isChecked())

    def Chagne_DEM_Apply(self):
        try:
            file_path=(self.txt_Cange_dem_File.text())
            time=self.spb_Change_DEM_Time.value()
            rowcount = self.tbl_DEM_File.rowCount()
            if rowcount ==0:
                self.tbl_DEM_File.setColumnCount(2)
                Dialog.tbl_DEM_File.setColumnWidth(0,90)
                Dialog.tbl_DEM_File.setColumnWidth(1,470)
                self.tbl_DEM_File.setHorizontalHeaderLabels(['Time [min]','DEMFile'])
                stylesheet = "::section{Background-color:rgb(225, 225, 225);}"
                self.tbl_DEM_File.horizontalHeader().setStyleSheet(stylesheet)

            if ChFile_Exists(file_path) and time>0: 
                self.tbl_DEM_File.insertRow(rowcount)
                self.tbl_DEM_File.setItem(rowcount, 0, QTableWidgetItem(str(time)))
                self.tbl_DEM_File.setItem(rowcount, 1, QTableWidgetItem(file_path))

            else:
                MsError("Invalid input value.")
                pass
        except Exception as e:
            MsError(e)

    def Clear_Table(self):
        self.tbl_DEM_File.setRowCount(0)
        self.tbl_Boundary.setRowCount(0)

    def Delete_Table_Data(self,table):
        try:
            reply = QMessageBox.question(None, 'G2D', 
                 'Are you sure you want to delete the selected data?', QMessageBox.Yes, QMessageBox.No)

            if reply == QMessageBox.Yes:
                row=table.currentRow()
                self.remove(table,row)
            else:
                pass
        except Exception as e:
            MsError(e)

    def remove(self,table,select_row):
        table.removeRow(select_row)

    def Add_Row_Boundary(self):
        try:
            rowcount = self.tbl_Boundary.rowCount()
            self.tbl_Boundary.insertRow(rowcount)
            #2019/11/18 박: 최박사님 요구사항 수정
            combo_box_options = ["Select Type","Discharge","Depth","Height"]
            #combo_box_options = ["Select Type","Discharge","Depth"]
            # 콤보 박스 셋팅
            combo = QComboBox()
            for t in combo_box_options:
                combo.addItem(t)
            self.tbl_Boundary.setCellWidget(rowcount,0,combo)
            self.tbl_Boundary.setItem(rowcount, 1, QTableWidgetItem(" "))
            btn = QPushButton()
            btn.setText('...')
            btn.clicked.connect(self.select_dialogs)
            self.tbl_Boundary.setCellWidget(rowcount,2, btn)
            self.tbl_Boundary.setItem(rowcount, 3, QTableWidgetItem(" "))

        except Exception as e:
            MsError(e)

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

    def Show_simulation_result(self):
        try:
            s = os.path.splitext(self.txt_dem.text())[0]+".prj"
            if ChFile_Exists(s):
                canvas=CanvasDialog(None,self.txt_dem.text(),G2DIni.Proj_File,"NO")
                canvas.exec_()
            else:
                 #DEM 에 PRJ 좌표계 파일이 없으면 프로세스 실행 하지 않고 PRJ 생성 창 오픈
                 #2019-09-23 박: 최박사님과 업무협의로 기능 변경 PRJ 파일 없으면 기능 실행 안함
                 MsInfo("PRJ files are required for DEM files.")
        except Exception as e:
            MsError(e)
    def Close_Form(self):
        self.close()

    def Set_makeimg(self):
        if self.chk_makeimg.isChecked() or self.chk_makeASCII.isChecked():
            self.chk_wdepth.setDisabled(False)
            self.chk_waterLevel.setDisabled(False)
            self.chk_velocity.setDisabled(False)            
            self.chk_discharge.setDisabled(False)
            self.chk_direction.setDisabled(False)
            #self.chk_Rainfall.setDisabled(False)
            #self.spb_Rainfall.setDisabled(False)

            self.spb_maxRenDepth.setDisabled(False)
            self.spb_maxRenLevel.setDisabled(False)
            self.spb_maxRenVelocity.setDisabled(False)
            self.spb_maxRenDischarge.setDisabled(False)

            #if self.chk_makeASCII.isChecked():
            #    self.spb_oPrecision_Depth.setEnabled(True)
            #    self.spb_oPrecision_WaterLevel.setEnabled(True)
            #    self.spb_oPrecision_Velocity.setEnabled(True)
            #    self.spb_oPrecision_Discharge.setEnabled(True)

            if self.chk_makeimg.isChecked():
                self.Check_chk_Output(self.chk_wdepth,self.spb_maxRenDepth_Velocity)
                self.Check_chk_Output(self.chk_waterLevel,self.spb_maxRenLevel)
                self.Check_chk_Output(self.chk_velocity,self.spb_maxRenVelocity)
                self.Check_chk_Output(self.chk_discharge,self.spb_maxRenDischarge)
                #self.Check_chk_Output(self.chk_Rainfall,self.spb_Rainfall)

            else:
                self.spb_maxRenDischarge.setDisabled(True)
                self.spb_maxRenDepth.setDisabled(True)
                self.spb_maxRenLevel.setDisabled(True)
                self.spb_maxRenVelocity.setDisabled(True)
                #self.spb_maxRenRainfall.setDisabled(True)

        elif not (self.chk_makeimg.isChecked()) and not (self.chk_makeASCII.isChecked()):
            self.chk_wdepth.setDisabled(False)
            self.chk_waterLevel.setDisabled(False)
            self.chk_velocity.setDisabled(False)
            self.chk_discharge.setDisabled(False)
            self.chk_direction.setDisabled(False)
            #self.chk_Rainfall.setDisabled(True)

            self.spb_maxRenDepth.setDisabled(True)
            self.spb_maxRenLevel.setDisabled(True)
            self.spb_maxRenVelocity.setDisabled(True)            
            self.spb_maxRenDischarge.setDisabled(True)            
            #self.spb_maxRenRainfall.setDisabled(True)

            #self.spb_oPrecision_Depth.setEnabled(False)
            #self.spb_oPrecision_WaterLevel.setEnabled(False)
            #self.spb_oPrecision_Velocity.setEnabled(False)
            #self.spb_oPrecision_Discharge.setEnabled(False)



    def Check_chk_Output(self,checkbox,spin):
        try:
            if (self.chk_makeimg.isChecked() or self.chk_makeASCII.isChecked()) and checkbox.isChecked():
                spin.setDisabled(False)
            else:
                spin.setDisabled(True)
        except Exception as e:
            MsError(e)


    def ChangeState_Output_options(self,checkbox,spin_rendererMax, spin_ouputPrecisions):
        try:            
            if checkbox.isChecked():
                spin_ouputPrecisions.setEnabled(True)
                if self.chk_makeimg.isChecked():
                    spin_rendererMax.setDisabled(False)
                else:
                    spin_rendererMax.setDisabled(True)
            else: 
                spin_ouputPrecisions.setEnabled(False)
                spin_rendererMax.setDisabled(True)

        except Exception as e:
            MsError(e)

    def set_tbl_Boundary(self):
        try:
            ##읽어온 파일 내용(XML)을 dictionary 로 변경
            #2019/11/18 박: 최박사님 요구사항 변경
            combo_box_options = ["Select Type","Discharge","Depth","Height"]
            getset = XMLCheck.Check_Gmp_xml(G2DIni.Proj_File)
            if getset.getBoundaryConditionData_Count()==0:
                self.tbl_Boundary.setRowCount(0)
                
                for index in range(12):
                    self.tbl_Boundary.insertRow(index)
                    combo = QComboBox()
                    for t in combo_box_options:
                        combo.addItem(t)
                    self.tbl_Boundary.setCellWidget(index,0,combo)
                    item1 = QTableWidgetItem(" ")
                    self.tbl_Boundary.setItem(index,1,item1)
                    btn = QPushButton()
                    btn.setText('...')
                    btn.clicked.connect(self.select_dialog)

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

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

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

                btn = QPushButton()
                btn.setText('...')
                btn.clicked.connect(self.select_dialog)
                self.tbl_Boundary.setCellWidget(0, 2, btn)
                self.tbl_Boundary.setItem(0, 3, QTableWidgetItem(str(CellXY)))
        except Exception as e:
            MsError(e)

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