'''
/***************************************************************************
Name	   :  new_name_controller.py
Description:  New Name controller class for FEWSTools plugin,
              updated from QGIS2
copyright  :  (C) 2019-2023 by FEWS
email      :  minxuansun@contractor.usgs.gov
Modified   :  07/26/2022 - cholen - Codebase consistency change
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 re

from PyQt5.QtWidgets import QMessageBox, QDialog

from fews_tools import fews_tools_config as config
from fews_tools.forms.Ui_NewName import Ui_NewName


class NewNameController(QDialog):
    '''
    Class for datasets controller
    '''
    def __init__(self, name_type):
        QDialog.__init__(self)
        self.ui = Ui_NewName()
        self.ui.setupUi(self)
        self.name_type = name_type
        self.ui.lblName.setText('New {} name:'.format(self.name_type))
        self.new_name = ''
        self.ui.lineEdit.setFocus()

        self.ui.okButton.clicked.connect(self.set_new_name)
        self.ui.cancelButton.clicked.connect(self.cancel)

    def __validate_input__(self):
        '''
        Validate the name entry
        '''
        err = False
        name_string = self.ui.lineEdit.text()
        if len(name_string) > config.MAX_CHARS or not\
                re.match(config.REG_EXPR_A, name_string):
            err = True
        if err is True:
            QMessageBox.critical(
                    self,
                    'Error in form',
                    'Error in name entry',
                    QMessageBox.Ok)
        return err

    def get_new_name(self):
        '''
        Get the widget value
        '''
        self.close()
        return self.new_name

    def set_new_name(self):
        '''
        Get the widget value
        '''
        err = self.__validate_input__()
        if not err:
            self.new_name = self.ui.lineEdit.text()
            self.close()

    def cancel(self):
        self.new_name = ''
        self.close()
