'''
/***************************************************************************
Name	   :  get_spatial_extents_controller.py
Description:  Get spatial extents class for FEWSTools plugin,
              updated from QGIS2
copyright  :  (C) 2019-2023 by FEWS
email      :  minxuansun@contractor.usgs.gov
Created    :  12/15/2019 - cholen
Modified   :  02/29/2020 - cholen - Adjust the 5 percent code
              05/01/2020 - cholen - Hide zoom extents selection
              10/22/2020 - cholen - Change wksp_info name to match other files
              02/23/2022 - cholen - Add tiff support
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 PyQt5.QtWidgets import QDialog, QFileDialog
from PyQt5.QtCore import Qt

from fews_tools.utilities import geoclim_qgs_utilities as qgs_util
from fews_tools import fews_tools_config as config

from fews_tools.models.region_model import RegionModel
from fews_tools.select_region import SelectRegion
from fews_tools.models.workspace_setup_model import WorkspaceSetupModel
from fews_tools.forms.Ui_GetSpatialExtent import Ui_GetSpatialExtent


class GetSpatialExtentsController(QDialog):
    '''
    Class for getting spatial extents from either a file or region definition
    using the Get Spatial Extents dialog
    param(list) - Db region info
    '''

    def __init__(self):
        QDialog.__init__(self)
        self.reg_ext_ui = Ui_GetSpatialExtent()
        self.reg_ext_ui.setupUi(self)
        self.reg_ext_ui.cancelButton.setFocus()

        self.extents = [0, 0, 0, 0]
        self.selected_file = None
        self.selected_region = None
        self.reg_info = RegionModel()
        self.wrksp_setup = WorkspaceSetupModel()
        self.reg_ext_ui.regionLineEdit.setText('')
        self.reg_ext_ui.browseButton.clicked.connect(self.choose_file)
        self.reg_ext_ui.okButton.clicked.connect(self.set_extents)
        self.reg_ext_ui.regionRadioButton.clicked.connect(
            self.choose_region)
        self.reg_ext_ui.okButton.setEnabled(False)
        self.reg_ext_ui.zoomRadioButton.setVisible(False)

    def choose_file(self):
        '''
        Function to browse to extents files.
        params(string): Raster or vector file
        returns(string): Path to the extents file.
        '''
        self.selected_region = None
        self.reg_ext_ui.regionLineEdit.setText('')
        if self.reg_ext_ui.rasterRadioButton.isChecked():
            file_types = config.RST_FILE_TYPES
            start_path = self.wrksp_setup.get_static_data_path()
        elif self.reg_ext_ui.vectorRadioButton.isChecked():
            file_types = config.VEC_FILE_TYPES
            start_path = self.wrksp_setup.get_map_data_path()
#        else:  # if self.reg_ext_ui.zoomRadioButton.isChecked():
#            file_types = config.VEC_FILE_TYPES
#            start_path = self.wrksp_setup.get_map_data_path()
        extents_tuple =\
            QFileDialog.getOpenFileName(self,
                                        'Select the Extents File',
                                        start_path,
                                        file_types)
        if extents_tuple is not None:
            self.selected_file = extents_tuple[0]
            self.reg_ext_ui.fileLineEdit.setText(
                os.path.basename(self.selected_file))
            self.reg_ext_ui.okButton.setEnabled(True)

    def choose_region(self):
        '''
        Opens a combo box to choose a region
        '''
        sel_region_dlg = SelectRegion()
        sel_region_dlg.exec_()
        self.selected_region = sel_region_dlg.get_region_name()

        if self.selected_region is not None:
            self.reg_ext_ui.okButton.setEnabled(True)
            self.reg_ext_ui.regionLineEdit.setText(self.selected_region)

    def get_extents(self):
        '''
        Gets the extents attributes(as a list)
        '''
        return self.extents

    def set_extents(self):
        '''
        Fill in extents from a selected map or region.
        '''
        FIVE_PCT = 0.05
        extents_temp = [0, 0, 0, 0]
        if self.selected_region is not None:
            self.reg_info.query_named_region(self.selected_region)
            reg_fields_dic = self.reg_info.get_region_dictionary()
            extents_temp[0] = reg_fields_dic['MinimumLatitude']
            extents_temp[1] = reg_fields_dic['MaximumLatitude']
            extents_temp[2] = reg_fields_dic['MinimumLongitude']
            extents_temp[3] = reg_fields_dic['MaximumLongitude']
        elif self.selected_file is not None:
            # handle raster selection
            if '.shp' not in self.selected_file:
                prop_tuple = qgs_util.extract_raster_file_params(
                    self.selected_file)
                extent_rectangle = prop_tuple[0]
                extents_temp[0] = extent_rectangle.yMinimum()
                extents_temp[1] = extent_rectangle.yMaximum()
                extents_temp[2] = extent_rectangle.xMinimum()
                extents_temp[3] = extent_rectangle.xMaximum()
            # extract vector extents...
            elif self.reg_ext_ui.vectorRadioButton.isChecked():
                v_extents = qgs_util.extract_shapefile_extents(
                    self.selected_file)
                # v_extents is (ymin, ymax, xmin, xmax)
                extents_temp[0] = v_extents[0]
                extents_temp[1] = v_extents[1]
                extents_temp[2] = v_extents[2]
                extents_temp[3] = v_extents[3]

#            else:   # self.reg_ext_ui.zoomRadioButton.isChecked():
#                QMessageBox.critical(self,
#                                     'Not implemented yet',
#                                     'Zoom Extents is not implemented yet!',
#                                     QMessageBox.Ok)
#                # just redo the vector until zoom is figured out
#                v_extents = qgs_util.extract_shapefile_extents(
#                    self.selected_file)
#                extents_temp[0] = v_extents[0]
#                extents_temp[1] = v_extents[1]
#                extents_temp[2] = v_extents[2]
#                extents_temp[3] = v_extents[3]

        # if box is checked, add 5%
        if self.reg_ext_ui.spExtentCheckBox.isChecked():
            lat_buffer = (extents_temp[1] - extents_temp[0]) * FIVE_PCT
            lon_buffer = (extents_temp[3] - extents_temp[2]) * FIVE_PCT
        else:
            lat_buffer = 0
            lon_buffer = 0
        self.extents[0] = round((extents_temp[0] - lat_buffer), 2)
        self.extents[1] = round((extents_temp[1] + lat_buffer), 2)
        self.extents[2] = round((extents_temp[2] - lon_buffer), 2)
        self.extents[3] = round((extents_temp[3] + lon_buffer), 2)
        self.close()
