# -*- coding: utf-8 -*-
"""
/***************************************************************************
 FlatDialog
                                 A QGIS plugin
 Flat
                             -------------------
        begin                : 2017-04-26
        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

from qgis.PyQt import QtWidgets
from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtWidgets import QFileDialog

from grm.FileFormat_dialog import FileFormat
from grm.lib.Regular_Expression import floatVerification, retrPdDayVerification
from grm.lib.Util import MsInfo
from grm.ui.AddFlowControl_dialog_base import Ui_FileFormatDialogBase


class AddFlowControl(QtWidgets.QDialog, Ui_FileFormatDialogBase):
    def __init__(
        self,
        _Project_Path="",
        _Flowcontrol_Edit_or_Insert_type="",
        _EditFlowName="",
        _EditFlowDT="",
        _EditFlowControlType="",
        _EditFlowFlowDataFile="",
        _EditFlowIniStorage="",
        _EditFlowMaxStorage="",
        _EditNomalHighStorage="",
        _EditRestrictedStorage="",
        _EditRetiPeriodSt="",
        _EditRetiPeriodEd="",
        _EditFlowROType="",
        _EditFlowAutoROMmaxOutflow_CMS="",
        _EditFlowROConstQ="",
        _EditFlowROConstQDuration="",
        _DataTimeFormat=True,  # grm_dialog_base.ui simulation 탭에서 set simulation starting time 체크박스 관련
        parent=None,
    ):
        super(AddFlowControl, self).__init__(parent)
        self.setupUi(self)

        self.project_path = _Project_Path
        self.datatimeFormat = _DataTimeFormat

        self._AddFlowcontrol_Edit_or_Insert_type = _Flowcontrol_Edit_or_Insert_type
        self._EditFlowName = _EditFlowName
        self._EditFlowDT = _EditFlowDT
        self._EditFlowControlType = _EditFlowControlType
        self._EditFlowFlowDataFile = _EditFlowFlowDataFile
        self._EditFlowIniStorage = _EditFlowIniStorage
        self._EditFlowMaxStorage = _EditFlowMaxStorage
        self._EditNomalHighStorage = _EditNomalHighStorage
        self._EditRestrictedStorage = _EditRestrictedStorage
        self._EditRetiPeriodSt = _EditRetiPeriodSt
        self._EditRetiPeriodEd = _EditRetiPeriodEd
        self._EditFlowROType = _EditFlowROType
        self._EditFlowAutoROMmaxOutflow_CMS = _EditFlowAutoROMmaxOutflow_CMS
        self._EditFlowROConstQ = _EditFlowROConstQ
        self._EditFlowROConstQDuration = _EditFlowROConstQDuration

        self._AddFlowcontrolFilePath = ""
        self._AddFlowcontrolType = ""
        self._AddFlowcontrolTimeInterval = ""
        self._AddFlowcontrolName = ""
        self._AddFlowcontrol_IniStorage = ""
        self._AddFlowcontrol_MaxStorage = "0"
        self._AddNomalHighStorage = "0"
        self._AddRestrictedStorage = "0"
        iniDate = "01M01D" if self.datatimeFormat else "0"
        self._AddRetiPeriodSt = iniDate
        self._AddRetiPeriodEd = iniDate
        self._AddFlowcontrol_ROType = ""
        self._AddFlowcontrol_AutoROMmaxOutflow_CMS = ""
        self._AddFlowcontrol_ROConstQ = ""
        self._AddFlowcontrol_ROConstQDuration = ""

        combolist = [
            "ReservoirOutflow",
            "Inlet",
            "ReservoirOperation",
            "SinkFlow",
            "SourceFlow",
        ]
        self.cmb_ControlType.addItems(combolist)
        self.cmb_ControlType.currentIndexChanged.connect(
            lambda: self.SelectControtype(
                self.cmb_ControlType,
                self.txt_TimeInterval,
                self.btnLoadFile,
                self.btnFileFormat,
                self.txtFilePath,
            )
        )
        self.preControlType = self.cmb_ControlType.currentText()

        self.btnLoadFile.clicked.connect(
            lambda: self.FileSelectDialog(self.txtFilePath)
        )
        self.btnFileFormat.clicked.connect(self.ViewFileFormat)
        self.rdoAutomatic.clicked.connect(self.ClickRdoAutomatic)
        self.txt_outflow_cms.setEnabled(False)
        self.txt_cms.setEnabled(False)
        self.txt_hours.setEnabled(False)
        self.txt_Constant_discharge.setEnabled(False)
        self.SelectControtype(
            self.cmb_ControlType,
            self.txt_TimeInterval,
            self.btnLoadFile,
            self.btnFileFormat,
            self.txtFilePath,
        )
        self.rdoAutomatic.setChecked(True)

        self.rdoRigid.clicked.connect(self.ClickRdoRigid)
        self.rdoUsingConstant.clicked.connect(self.ClickRdoUsingConstant)
        self.btnCancel.clicked.connect(lambda: self.Close_Form(False, "cancel"))
        self.btnOK.clicked.connect(self.Ok_click)

        if self._AddFlowcontrol_Edit_or_Insert_type != "Insert":
            self.SetControlData()

        self.setWindowFlags(Qt.Window | Qt.WindowTitleHint | Qt.CustomizeWindowHint)
        self.groupBox_5.setStyleSheet("QGroupBox{padding-top:15px;margin-top:-15px;}")

    def SelectControtype(
        self, combox, txtinterval, btnLoadFile, btnFileFormat, txtFilePath
    ):
        crtTxt = combox.currentText()
        if crtTxt == "ReservoirOperation":
            self.groupBox_4.setEnabled(False)  # set flow data
            self.groupBox_3.setEnabled(True)  # reservoir operation
            self.groupBox_2.setEnabled(True)
            self.txt_TimeInterval.setEnabled(False)

            if self.rdoAutomatic.isChecked():
                self.txt_outflow_cms.setEnabled(True)
                self.txt_outflow_cms.setText(self._EditFlowAutoROMmaxOutflow_CMS)
                self.txt_cms.setEnabled(False)
                self.txt_Constant_discharge.setEnabled(False)
                self.txt_hours.setEnabled(False)
            elif self.rdoRigid.isChecked():
                self.txt_cms.setText(self._EditFlowROConstQ)
                self.ClickRdoRigid()
            elif self.rdoUsingConstant.isChecked():
                self.rdoUsingConstant.setChecked(True)
                self.txt_Constant_discharge.setText(self._EditFlowROConstQ)
                self.txt_hours.setText(self._EditFlowROConstQDuration)
                self.ClickRdoUsingConstant()
        elif crtTxt in ["SinkFlow", "SourceFlow", "Inlet"]:
            self.groupBox_4.setEnabled(True)
            self.groupBox_3.setEnabled(False)
            self.groupBox_2.setEnabled(False)
            self.txt_TimeInterval.setEnabled(True)
        else:
            self.groupBox_4.setEnabled(True)
            self.groupBox_3.setEnabled(False)
            self.groupBox_2.setEnabled(True)
            self.txt_TimeInterval.setEnabled(True)

        if (
            self.preControlType == "ReservoirOperation"
            or crtTxt == "ReservoirOperation"
        ):
            self.txtFilePath.setText("")

    def FileSelectDialog(self, txtpath):
        txtpath.clear()
        dir = os.path.dirname(os.path.realpath(self.project_path))
        self.filename = QFileDialog.getOpenFileName(self, "select file ", dir, "*.txt")[
            0
        ]
        txtpath.setText(self.filename)

    def ClickRdoAutomatic(self):
        self.txt_outflow_cms.setEnabled(True)
        self.txt_cms.setEnabled(False)
        self.txt_hours.setEnabled(False)
        self.txt_Constant_discharge.setEnabled(False)

    def ClickRdoRigid(self):
        self.txt_outflow_cms.setEnabled(False)
        self.txt_cms.setEnabled(True)
        self.txt_hours.setEnabled(False)
        self.txt_Constant_discharge.setEnabled(False)

    def ClickRdoUsingConstant(self):
        self.txt_outflow_cms.setEnabled(False)
        self.txt_cms.setEnabled(False)
        self.txt_hours.setEnabled(True)
        self.txt_Constant_discharge.setEnabled(True)

    def ViewFileFormat(self):
        results = FileFormat()
        results.exec_()

    def Close_Form(self, OkCancel, insert_edit):
        if OkCancel:
            self._AddFlowcontrol_Edit_or_Insert_type = insert_edit
            self.close()
        else:
            self._AddFlowcontrol_Edit_or_Insert_type = "cancel"
            self.close()

    def keyPressEvent(self, e):
        if e.key() == 16777216:
            pass

    def Ok_click(self):
        if self._AddFlowcontrol_Edit_or_Insert_type == "Insert":
            if self.txt_Name.text().strip() == "":
                MsInfo(" Input name, please")
                self.txt_Name.setFocus()
                return
            else:
                self._AddFlowcontrolName = self.txt_Name.text()

            self._AddFlowcontrolType = self.cmb_ControlType.currentText()
            if self.txt_TimeInterval.text().strip() == "":
                MsInfo(" Please enter a time interval")
                self.txt_TimeInterval.setFocus()
                return
            else:
                if self.txt_TimeInterval.text().isdigit():
                    self._AddFlowcontrolTimeInterval = self.txt_TimeInterval.text()
                else:
                    MsInfo(" Please enter a time interval")
                    self.txt_TimeInterval.setFocus()
                    return

            if self.cmb_ControlType.currentText() != "ReservoirOperation":
                if self.txtFilePath.text() == "":
                    MsInfo("Please enter only numbers")
                    self.txtFilePath.setFocus()
                    return
                else:
                    self._AddFlowcontrolFilePath = self.txtFilePath.text()
            else:
                #                 self._AddFlowcontrolFilePath = "ResurvoirOperation"
                self._AddFlowcontrolFilePath = ""

            rst = self.confirmFlowValue()
            if not rst:
                return
            retrStrSt, retrStrEd, inistorg, maxstorg, nomalstorg, retrstorg = rst

            self._AddFlowcontrol_IniStorage = inistorg
            self._AddFlowcontrol_MaxStorage = maxstorg
            self._AddNomalHighStorage = nomalstorg
            self._AddRestrictedStorage = retrstorg
            self._AddRetiPeriodSt = retrStrSt
            self._AddRetiPeriodEd = retrStrEd

            if self.cmb_ControlType.currentText() == "ReservoirOperation":
                if self.rdoAutomatic.isChecked():
                    self._AddFlowcontrol_ROType = "AutoROM"
                    self._AddFlowcontrol_AutoROMmaxOutflow_CMS = (
                        self.txt_outflow_cms.text()
                    )

                elif self.rdoRigid.isChecked():
                    self._AddFlowcontrol_ROType = "RigidROM"
                    self._AddFlowcontrol_ROConstQ = self.txt_cms.text()
                    self._AddFlowcontrol_ROConstQDuration = ""

                elif self.rdoUsingConstant.isChecked():
                    self._AddFlowcontrol_ROType = "ConstantQ"
                    self._AddFlowcontrol_ROConstQ = self.txt_Constant_discharge.text()
                    self._AddFlowcontrol_ROConstQDuration = self.txt_hours.text()
            else:
                self._AddFlowcontrol_ROType = ""
                self._AddFlowcontrol_ROConstQ = ""
                self._AddFlowcontrol_ROConstQDuration = ""

            self._Flowcontrolgrid_flag_Insert = True
            self.Close_Form(True, self._AddFlowcontrol_Edit_or_Insert_type)

        else:
            if self.txt_Name.text() == "":
                MsInfo(" Input name, please")
                self.txt_Name.setFocus()
                return
            else:
                self._EditFlowName = self.txt_Name.text()

            self._EditFlowControlType = self.cmb_ControlType.currentText()

            if self.txt_TimeInterval.text() == "":
                MsInfo(" Please enter a time interval")
                self.txt_TimeInterval.setFocus()
                return
            else:
                self._EditFlowDT = self.txt_TimeInterval.text()

            if self.cmb_ControlType.currentText() != "ReservoirOperation":
                if self.txtFilePath.text() == "":
                    MsInfo(" Please set file path")
                    self.txtFilePath.setFocus()
                    return
                else:
                    self._EditFlowFlowDataFile = self.txtFilePath.text()
            else:
                #                 self._EditFlowFlowDataFile = "ResurvoirOperation"
                self._EditFlowFlowDataFile = ""

            rst = self.confirmFlowValue()
            if not rst:
                return
            retrStrSt, retrStrEd, inistorg, maxstorg, nomalstorg, retrstorg = rst

            self._EditFlowIniStorage = inistorg
            self._EditFlowMaxStorage = maxstorg
            self._EditNomalHighStorage = nomalstorg
            self._EditRestrictedStorage = retrstorg
            self._EditRetiPeriodSt = retrStrSt
            self._EditRetiPeriodEd = retrStrEd

            if self.cmb_ControlType.currentText() == "ReservoirOperation":
                if self.rdoAutomatic.isChecked():
                    self._EditFlowROType = "AutoROM"
                    self._EditFlowAutoROMmaxOutflow_CMS = self.txt_outflow_cms.text()

                elif self.rdoRigid.isChecked():
                    self._EditFlowROType = "RigidROM"
                    self._EditFlowROConstQ = self.txt_cms.text()
                    self._EditFlowROConstQDuration = ""

                elif self.rdoUsingConstant.isChecked():
                    self._EditFlowROType = "ConstantQ"
                    self._EditFlowROConstQ = self.txt_Constant_discharge.text()
                    self._EditFlowROConstQDuration = self.txt_hours.text()
            else:
                self._EditFlowROType = ""
                self._EditFlowAutoROMmaxOutflow_CMS = ""
                self._EditFlowROConstQ = ""
                self._EditFlowROConstQDuration = ""

            self.Close_Form(True, self._AddFlowcontrol_Edit_or_Insert_type)

    def confirmFlowValue(self):
        retrStrSt = self.txtRetiPeriodSt.text().strip().upper()
        retrStrEd = self.txtRetiPeriodEd.text().strip().upper()
        inistorg = self.txtIniStorage.text().strip()
        maxstorg = self.txtMaxStorage.text().strip()
        nomalstorg = self.txtNomalHighStorage.text().strip()
        retrstorg = self.txtRestrictedStorage.text().strip()
        l = [retrStrSt, retrStrEd, inistorg, maxstorg, nomalstorg, retrstorg]

        for sto in l[2:]:
            if sto and not floatVerification(sto):
                MsInfo("Enter a number in Storage.")
                return False
        if (
            (l[:2] != [""] * 2)
            and (self.datatimeFormat)
            and (
                not retrPdDayVerification(retrStrSt)
                or not retrPdDayVerification(retrStrEd)
            )
        ):
            MsInfo(
                " Enter the Restricted period in the following format. \n ex) 01M01D"
            )
            return False
        elif (
            (l[:2] != [""] * 2)
            and (not self.datatimeFormat)
            and (not floatVerification(retrStrSt) or not floatVerification(retrStrEd))
        ):  # 숫자형식
            MsInfo(" Enter a number in Restricted period. ")
            return False

        for i, j in enumerate(l):
            if self.datatimeFormat and i < 2 and not j:
                l[i] = "01M01D"
            elif (not self.datatimeFormat and i < 2 and not j) or i > 2 and not j:
                l[i] = "0"

        return l

    def SetControlData(self):
        self.txt_Name.setText(self._EditFlowName)
        controltype = self._EditFlowControlType
        index = self.cmb_ControlType.findText(str(controltype), Qt.MatchFixedString)
        if index >= 0:
            self.cmb_ControlType.setCurrentIndex(index)
        self.txt_TimeInterval.setText(self._EditFlowDT)
        self.txtFilePath.setText(self._EditFlowFlowDataFile)
        self.txtIniStorage.setText(self._EditFlowIniStorage)
        self.txtMaxStorage.setText(self._EditFlowMaxStorage)
        self.txtNomalHighStorage.setText(self._EditNomalHighStorage)
        self.txtRestrictedStorage.setText(self._EditRestrictedStorage)
        self.txtRetiPeriodSt.setText(self._EditRetiPeriodSt)
        self.txtRetiPeriodEd.setText(self._EditRetiPeriodEd)

        if self._EditFlowROType == "AutoROM":
            self.rdoAutomatic.setChecked(True)
            self.txt_outflow_cms.setText(self._EditFlowAutoROMmaxOutflow_CMS)
            self.ClickRdoAutomatic()
        elif self._EditFlowROType == "RigidROM":
            self.rdoRigid.setChecked(True)
            self.txt_cms.setText(self._EditFlowROConstQ)
            self.ClickRdoRigid()
        elif self._EditFlowROType == "ConstantQ":
            self.rdoUsingConstant.setChecked(True)
            self.txt_Constant_discharge.setText(self._EditFlowROConstQ)
            self.txt_hours.setText(self._EditFlowROConstQDuration)
            self.ClickRdoUsingConstant()
