# -*- coding: utf-8 -*-
"""
/***************************************************************************
 GRMDockWidget
                                 A QGIS plugin
 GRM
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2020-01-08
        git sha              : $Format:%H$
        copyright            : (C) 2020 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 sys


from qgis.PyQt import QtGui, QtWidgets, uic
from qgis.PyQt.QtCore import pyqtSignal 
from qgis.core import *

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

import webbrowser
from .lib.Util import *
from .XMLCheck import xmls
from .XMLMake import make
from .lib.xmltodict import *
from .lib.File_Class import *

from .GRM_dialog import GRMDialog
from .Rainfall_dialog import RainFallDialog
from .Watershed_dialog import WatershedDialog
from .LandCover_dialog import LandCoverDialog
import time


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

path = os.path.dirname(os.path.realpath(__file__))
Project = path +'\image\Folder_3.png'
InputData =  path +'\image\database.png'
RunGRM =  path +'\image\settings.png'
GRMTools = path + '\image\Tool.png'
Help =  path +'\image\information.png'
Analysis =  path +'\image\Analysis.png'
Flask =  path +'\image\Flask.png'

_XmlCheck = xmls()
_XmlCreat = make()
#트리 위제 목록이 비활성화 중에도 클릭 이벤트가 처리 되는 현상으로 
#구분 하기위해서 넣음
_ProjectFlage = False


class GRMDockWidget(QtWidgets.QDockWidget, FORM_CLASS):

    closingPlugin = pyqtSignal()

    def __init__(self, parent=None):
        super(GRMDockWidget, self).__init__(parent)
        self.setupUi(self)

        # 화면 초기화
        self.initUI()

    def initUI(self):

        MsTitle("GRM")
        self.setWindowTitle("GRM")
        self.treeWidget.setItemsExpandable(True)
        self.treeWidget.setAnimated(True)
        self.treeWidget.setItemsExpandable(True)
        self.treeWidget.setColumnCount(1)
        self.treeWidget.setHeaderLabels([''])

        # Qtree 박스에 헤더 부분 제거
        self.treeWidget.setHeaderHidden(True)

        #아이템 메뉴 설정
        item0 = QTreeWidgetItem(self.treeWidget, ['Project'])
        item01 = QTreeWidgetItem(item0, ['New Project'])
        item02 = QTreeWidgetItem(item0, ['Open Project'])
        item03 = QTreeWidgetItem(item0, ['Save Project'])
        item03.setDisabled(True)
        item04 = QTreeWidgetItem(item0, ['Save As Project'])
        item04.setDisabled(True)
        icon = QtGui.QIcon(Project)
        item0.setIcon(0, icon)

        item1 =QTreeWidgetItem(self.treeWidget, ['Setup input data'])
        item11 =QTreeWidgetItem(item1, ['Watershed'])
        item12 =QTreeWidgetItem(item1, ['Land Cover / Soil'])
        item13 =QTreeWidgetItem(item1, ['Rainfall'])
        icon =QtGui.QIcon(InputData)
        item1.setIcon(0, icon)
        item1.setDisabled(True)

        #item2 =QTreeWidgetItem(self.treeWidget, ['Run GRM'])
        item2 =QTreeWidgetItem(self.treeWidget, ['Setup / Run GRM'])
        #item21 =QTreeWidgetItem(item2, ['Setup / Run GRM'])
        icon =QtGui.QIcon(RunGRM)
        item2.setIcon(0, icon)
        item2.setDisabled(True)

  
        item5 =QTreeWidgetItem(self.treeWidget, ['Help'])
        item51 =QTreeWidgetItem(item5, ['Helps'])
        #아이콘 설정
        icon =QtGui.QIcon(Help)
        item5.setIcon(0, icon)

        self.grmDialogFlag = False

        self.mainLayout =QGridLayout(self)
        self.mainLayout.addWidget(self.treeWidget)
        
        # 더블 클릭 했을대 메뉴 명칭 확인
        self.treeWidget.itemDoubleClicked.connect(self.OnDoubleClick)


    def OnDoubleClick(self, item):
        try:
            SelectItme = item.text(0)
            # 프로젝트 파일 오픈
            if SelectItme=="New Project":
                self.NewProjectFile()

            elif SelectItme == 'Open Project':
                self.OpenProjectFile()

            elif SelectItme =="Save Project":
                if _ProjectFlage:
                    self.SaveProjectFile()

            elif SelectItme =="Save As Project":
                if _ProjectFlage:
                    self.SaveASProjectFile()
            
            
            elif SelectItme=='Watershed':
                if _ProjectFlage:
                    if (self.grmDialogFlag==True): self._grmDialogFlag=1
                    if (self.grmDialogFlag==False): self._grmDialogFlag=0
                    Watershed = WatershedDialog(self._xmltodict, self._grmDialogFlag)
                    Watershed.exec_()
                    self._xmltodict=Watershed._xmltodict
                    self._grmDialogFlag=Watershed._grmDialogFlag


            elif SelectItme =="Land Cover / Soil":
                if _ProjectFlage:
                    if (self.grmDialogFlag==True): self._grmDialogFlag=1
                    if (self.grmDialogFlag==False): self._grmDialogFlag=0
                    LandCover = LandCoverDialog(self._xmltodict,self._LandCoverCount,self._GreenAmptCount,self._SoilDepthCount,self._grmDialogFlag)
                    LandCover.exec_()
                    self._xmltodict=LandCover._xmltodict
                    self._LandCoverCount=LandCover._LandCoverCount
                    self._GreenAmptCount = LandCover._GreenAmptCount
                    self._SoilDepthCount = LandCover._SoilDepthCount
                    self._grmDialogFlag=LandCover._grmDialogFlag

            elif SelectItme =="Rainfall":
                if _ProjectFlage:
                    RainFall = RainFallDialog(self._xmltodict)
                    RainFall.exec_()
                    self._xmltodict=RainFall._xmltodict

            elif SelectItme == 'Setup / Run GRM':
                if _ProjectFlage:
                    try:
                        #2022.01.05 동 : flag를 사용하지 않으면 GRMDialog 창이 클릭한 개수만큼 뜨게 됨. 
                        # 창이 여러개 뜨면 grid line, flow direction을 캔버스에 표시할때 오류가 발생해서 1개의 창만 킬 수 있도록 변경
                        # 그 외, 개발할때 reload plugin 하기 전에 dialog 창이 켜진 상태로 reload를 진행하면 기존 레이어가 지워지지 않아서 오류가 발생할 수 있음.
                        def closeSignal():
                            self.grmDialogFlag = False

                        if not self.grmDialogFlag:
                            GRM = GRMDialog( self._xmltodict, self._WatchPointCount, self._SubWatershedCount, 
                                         self._GreenAmptCount, self._SoilDepthCount, self._LandCoverCount, 
                                         self._FlowControlCount, self._ChannelSettingsCount)
                            
                            GRM.closeDialogEvent.connect(closeSignal)
                            GRM.show()
                            self.grmDialogFlag = True
                        
                            self._xmltodict= GRM._xmltodict
                    except AttributeError as e:
                        MsError("All input data is not set.")
                    
            elif SelectItme == "Helps":
                iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),"Internet Explorer\\IEXPLORE.EXE")
                ie = webbrowser.BackgroundBrowser(iexplore)
                ie.open("https://docs.google.com/document/d/15vySQ7c6e2fnKsJtovMoA7n9PoY7gnfdoUKRowD_vYY/edit")
        
        except Exception as e:
            self.grmDialogFlag = False
            MsError(e)



    def AddLayerQGIS(self):
        # dictionary 값을 받아서 레이어 목록을 Qgis 에 올림
        tag = ['DomainFile', 'SlopeFile', 'FlowDirectionFile', 'FlowAccumFile', 
               'StreamFile', 'LandCoverFile', 'SoilDepthFile', 'SoilTextureFile']
        
        for t in tag:
            if self._xmltodict['GRMProject']['ProjectSettings'][t] is not None:
                self.AddlayerQGIS(self._xmltodict['GRMProject']['ProjectSettings'][t])


    def NewProjectFile(self):

        self._SubWatershedCount = 0
        self._WatchPointCount = 0
        self._FlowControlCount = 0
        self._GreenAmptCount = 0
        self._SoilDepthCount = 0
        self._LandCoverCount = 0
        self._RainFallCount=0

        #2020-04-21 박: 추가 항목 
        self._ChannelSettingsCount=0


        # New Project 시에 GMP 파일 새로 생성
        filename = QFileDialog.getSaveFileName(self, "select output file ", "", "*.gmp")[0]

        if filename:
            self._ProjectFile = filename
            _XmlCreat.Make_GMP_File(filename)
            if len(filename) > 0:
                self.clear()
            Projectfile = open(filename, 'r')
            data = Projectfile.read()
            Projectfile.close()
#             self.indent(filename)
            time.sleep(1)
            if ChFile_Exists(filename):
                MsInfo("[" + str(self._ProjectFile) + "]" + " GMP file created. ")
            else:
                MsError("The GMP file creation failed.")
            self._xmltodict = dict(parse(data))
            self._xmltodict = self._xmltodict
        else:
            return




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


    def OpenProjectFile(self):
        # 프로젝트 파일 찾을 다이얼 로그
        try:
            #프로젝트 파일 불러오기
            self.filename = QFileDialog.getOpenFileName(self,'select output file','','GRM Project xml files (*.gmp)',options=QFileDialog.DontUseNativeDialog)[0]
            if ChFile_Exists(self.filename):
                self._ProjectFile = self.filename

                #2020-02-10 박: XML 체크할때 Landcover 데이터를 배열에 받아서 반환 함
                 
                _XmlCheck.Check_Gmp_xml(self._ProjectFile)
                time.sleep(1)
                self._LandCoverCount =_XmlCheck._LandCoverCount
                self._GreenAmptCount =_XmlCheck._GreenAmptCount
                self._SoilDepthCount =_XmlCheck._SoilDepthCount
                self._WatchPointCount = _XmlCheck._WatchPointCount
                self._SubWatershedCount=_XmlCheck._SubWatershedCount
                self._GreenAmptCount = _XmlCheck._GreenAmptCount
                self._SoilDepthCount = _XmlCheck._SoilDepthCount
                self._LandCoverCount =_XmlCheck._LandCoverCount
                self._FlowControlCount = _XmlCheck._FlowControlCount
                self._ChannelSettingsCount=_XmlCheck._ChannelSettingsCount

                # 프로젝트 파일 확인 후에 QtreeWidget 재설정(비활성화 메뉴 활성화)
                if len(self.filename)>0:
                    self.clear()

                ## 2017/09/17 프로젝트 파일(XML)을 그냥 일반 문서 처럼 읽어옴
                Projectfile = open(self.filename, 'r')
                data = Projectfile.read()
                Projectfile.close()

                # 읽어온 파일 내용(XML)을 dictionary 로 변경
                self._xmltodict = dict(parse(data))

                # dictionary 값을 받아서 레이어 목록을 Qgis 에 올림
                if self._xmltodict['GRMProject']['ProjectSettings']['DomainFile'] is not None:
                    self.AddlayerQGIS(self._xmltodict['GRMProject']['ProjectSettings']['DomainFile'])

                if self._xmltodict['GRMProject']['ProjectSettings']['SlopeFile'] is not None:
                    self.AddlayerQGIS(self._xmltodict['GRMProject']['ProjectSettings']['SlopeFile'])

                if self._xmltodict['GRMProject']['ProjectSettings']['FlowDirectionFile'] is not None:
                    self.AddlayerQGIS(self._xmltodict['GRMProject']['ProjectSettings']['FlowDirectionFile'])

                if self._xmltodict['GRMProject']['ProjectSettings']['FlowAccumFile'] is not None:
                    self.AddlayerQGIS(self._xmltodict['GRMProject']['ProjectSettings']['FlowAccumFile'])

                if self._xmltodict['GRMProject']['ProjectSettings']['StreamFile'] is not None:
                    self.AddlayerQGIS(self._xmltodict['GRMProject']['ProjectSettings']['StreamFile'])

                if self._xmltodict['GRMProject']['ProjectSettings']['LandCoverFile'] is not None:
                    self.AddlayerQGIS(self._xmltodict['GRMProject']['ProjectSettings']['LandCoverFile'])

                if self._xmltodict['GRMProject']['ProjectSettings']['SoilDepthFile'] is not None:
                    self.AddlayerQGIS(self._xmltodict['GRMProject']['ProjectSettings']['SoilDepthFile'])

                if self._xmltodict['GRMProject']['ProjectSettings']['SoilTextureFile'] is not None:
                    self.AddlayerQGIS(self._xmltodict['GRMProject']['ProjectSettings']['SoilTextureFile'])

                # 현재 열은 프로젝트 파일 경로와 GMP 내부 프로젝트 파일 경로 동기화
                self._xmltodict['GRMProject']['ProjectSettings']['ProjectFile'] = self._ProjectFile
        except Exception as wa:
            MsError(wa)

    def SaveProjectFile(self):
        DictoXml = unparse(self._xmltodict)
        fw = open(self._ProjectFile, 'w+')
        fw.write(DictoXml)
        fw.close()

        #2020-02-10 박: XML 체크할때 Landcover 데이터를 배열에 받아서 반환 함 
        _XmlCheck.Check_Gmp_xml(self._ProjectFile)
        time.sleep(1)
        self._LandCoverCount =_XmlCheck._LandCoverCount
        self._GreenAmptCount =_XmlCheck._GreenAmptCount
        self._SoilDepthCount =_XmlCheck._SoilDepthCount
        self._WatchPointCount = _XmlCheck._WatchPointCount
        self._SubWatershedCount=_XmlCheck._SubWatershedCount
        self._FlowControlCount = _XmlCheck._FlowControlCount
        self._ChannelSettingsCount=_XmlCheck._ChannelSettingsCount


        ## 2017/09/17 프로젝트 파일(XML)을 그냥 일반 문서 처럼 읽어옴
        Projectfile = open(self._ProjectFile, 'r')
        data = Projectfile.read()
        Projectfile.close()

        # 읽어온 파일 내용(XML)을 dictionary 로 변경
        self._xmltodict = dict(parse(data))
        MsInfo( '[' + self._ProjectFile + '] ' + 'was saved. ')

    def SaveASProjectFile(self):
        SaveAsPath = QFileDialog.getSaveFileName(self, "select output file ", "", "*.gmp")[0]
        if SaveAsPath=="":
            MsInfo("[" + str(self._ProjectFile) + "]" + " Save was cancelled. ")
            return
        else :
            self._xmltodict['GRMProject']['ProjectSettings']['ProjectFile'] =SaveAsPath
            self._ProjectFile = SaveAsPath
            DictoXml = unparse(self._xmltodict)
            fw = open(self._ProjectFile, 'w+')
            fw.write(DictoXml)
            fw.close()
#             self.indent(self._ProjectFile)
            time.sleep(1)
            #2020-02-10 박: XML 체크할때 Landcover 데이터를 배열에 받아서 반환 함 
            _XmlCheck.Check_Gmp_xml(self._ProjectFile)
               
            self._LandCoverCount =_XmlCheck._LandCoverCount
            self._GreenAmptCount =_XmlCheck._GreenAmptCount
            self._SoilDepthCount =_XmlCheck._SoilDepthCount
            self._WatchPointCount = _XmlCheck._WatchPointCount
            self._SubWatershedCount=_XmlCheck._SubWatershedCount
            self._GreenAmptCount = _XmlCheck._GreenAmptCount
            self._SoilDepthCount = _XmlCheck._SoilDepthCount
            self._LandCoverCount =_XmlCheck._LandCoverCount
            self._FlowControlCount = _XmlCheck._FlowControlCount
            self._ChannelSettingsCount=_XmlCheck._ChannelSettingsCount

            ## 2017/09/17 프로젝트 파일(XML)을 그냥 일반 문서 처럼 읽어옴
            Projectfile = open(self._ProjectFile, 'r')
            data = Projectfile.read()
            Projectfile.close()
            # 읽어온 파일 내용(XML)을 dictionary 로 변경
            self._xmltodict = dict(parse(data))

            MsInfo( '[' + self._ProjectFile + ']' + ' was saved. ')
    # gis에 올리기
    def AddlayerQGIS(self, path):
        if (os.path.isfile(path)) and (self.CheckLayer(path)):
            fileInfo = QFileInfo(path)
            baseName = fileInfo.baseName()
            layer=QgsRasterLayer(path, baseName, "gdal")
            QgsProject.instance().addMapLayer(layer)

    # 레이어가 Qgis에 올라와 있는지 확인 (현재 QGIS에 올라온 레이어면 올리지 않음)
    def CheckLayer(self, layerpath):
        for lyr in QgsProject.instance().mapLayers().values():
            if lyr.dataProvider().dataSourceUri().upper() == layerpath.upper():
                return False
        return True

    # tree widget 초기화 시키고 다시 메뉴 셋팅(프로젝트 파일 로드후 비활성화 메뉴 활성화로 변경)
    def clear(self):
        self.treeWidget.clear()
        self.Newset()

    def Newset(self):
        # 트리 메뉴가 비활성화 되어도 더블클릭 이베트가 먹히는 현상으로 인해 플래그 설정
        global _ProjectFlage
        _ProjectFlage = True

        # treeWidget refresh 문제로 메뉴 항목 재설정
        self.setWindowTitle("GRM")

        # Qtree 박스에 헤더 부분 제거
        self.treeWidget.setHeaderHidden(True)

        item0 = QTreeWidgetItem(self.treeWidget, ['Project'])
        item01 = QTreeWidgetItem(item0, ['New Project'])
        item02 = QTreeWidgetItem(item0, ['Open Project'])
        item03 = QTreeWidgetItem(item0, ['Save Project'])
        item04 = QTreeWidgetItem(item0, ['Save As Project'])
        icon = QtGui.QIcon(Project)
        item0.setIcon(0, icon)

        item1 = QTreeWidgetItem(self.treeWidget, ['Setup input data'])
        item11 = QTreeWidgetItem(item1, ['Watershed'])
        item12 = QTreeWidgetItem(item1, ['Land Cover / Soil'])
        item13 = QTreeWidgetItem(item1, ['Rainfall'])
        icon = QtGui.QIcon(InputData)
        item1.setIcon(0, icon)

        #item2 = QTreeWidgetItem(self.treeWidget, ['Run GRM'])
        item2 = QTreeWidgetItem(self.treeWidget, ['Setup / Run GRM'])
        #item21 = QTreeWidgetItem(item2, ['Setup / Run GRM'])
        icon = QtGui.QIcon(RunGRM)
        item2.setIcon(0, icon)

        item5 =QTreeWidgetItem(self.treeWidget, ['Help'])
        item51 =QTreeWidgetItem(item5, ['Helps'])
        #아이콘 설정
        icon =QtGui.QIcon(Help)
        item5.setIcon(0, icon)

        self.mainLayout = QGridLayout(self)
        self.mainLayout.addWidget(self.treeWidget)

    def closeEvent(self, event):
        self.closingPlugin.emit()
        event.accept()




