"""
/***************************************************************************
Name            :  animation_utilities.py
Description     :  Data animation utilities class for FEWSTools plugin,
                        updated from QGIS2
copyright       :  (C) 2022-2023 by FEWS
email           :  jhowton@contractor.usgs.gov
Created         :  10/25/2022 - jhowton
Modified        :
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 datetime
import math
import os
import re

from PyQt5 import QtWidgets
from qgis.core import QgsProject, QgsRasterLayerTemporalProperties
from qgis.core import QgsDateTimeRange
from qgis.utils import iface

from fews_tools.utilities import date_utilities


def set_temporal(layer, time_start, time_end):
    """
    Set a temporal range for raster layer
    :param layer: raster layer
    :param time_start: time start
    :param time_end: time end
    """
    tprops = layer.temporalProperties()
    tprops.setMode(QgsRasterLayerTemporalProperties.ModeFixedTemporalRange)

    tprops.setFixedTemporalRange(QgsDateTimeRange(time_start, time_end))
    tprops.setIsActive(True)


def get_file_info(fname):
    '''
    Strip and return the basename, year, and period

    :param fname: input filename
    :return basename: the basename of the input file
    :return year: the year pulled from the basename
    :return period: the period pulled from the basename
    '''
    basename, _ = os.path.splitext(os.path.basename(fname))

    year_period = re.search(r'.*(\d{4}).*(\d{2})', fname)
    year = year_period.group(1)
    period = year_period.group(2)
    return basename, year, period


def setup_animation(file_list, period_type):
    '''
    Function to set up temporal extents for a list of files

    param: file_list: list of input files
    param: dekad: boolian toggle for if the data is dekadal or pentadal
    '''
    period_type = period_type.lower()
    for index, _ in enumerate(file_list):
        basename, year, period = get_file_info(file_list[index])

        if period_type == "dekadal":
            month = math.ceil(int(period) / 3)
            start_day, end_day = date_utilities.get_dekad_start_and_end_days(
                {'DATADATEFORMAT': 'YYYYEK'}, year + period)

        elif period_type == "pentadal":
            month = math.ceil(int(period) / 6)
            start_day, end_day = date_utilities.get_pentad_start_and_end_days(
                {'DATADATEFORMAT': 'YYYYPT'}, year + period)

        set_temporal(QgsProject.instance().mapLayersByName(basename)[0],
                     datetime.datetime(int(year), int(
                         month), start_day.day, 0, 0, 0),
                     datetime.datetime(int(year), month, end_day.day,
                                       23, 59, 59))


def set_start_end(file_list, period_type):
    '''
    Function to display the temporal controller panel and set the start and
    end dates.

    param: file_list: list of input files
    param: dekad: boolian toggle for if the data is dekadal or pentadal
    '''
    period_type = period_type.lower()
    _, first_year, first_period = get_file_info(file_list[0])
    _, last_year, last_period = get_file_info(file_list[len(file_list) - 1])

    if period_type == "dekadal":
        first_month = math.ceil(int(first_period) / 3)
        last_month = math.ceil(int(last_period) / 3)

        start_day, _ = date_utilities.get_dekad_start_and_end_days(
            {'DATADATEFORMAT': 'YYYYEK'}, first_year + first_period)
        _, end_day = date_utilities.get_dekad_start_and_end_days(
            {'DATADATEFORMAT': 'YYYYEK'}, last_year + last_period)

    elif period_type == "pentadal":
        first_month = math.ceil(int(first_period) / 6)
        last_month = math.ceil(int(last_period) / 6)

        start_day, _ = date_utilities.get_pentad_start_and_end_days(
            {'DATADATEFORMAT': 'YYYYPT'}, first_year + first_period)
        _, end_day = date_utilities.get_pentad_start_and_end_days(
            {'DATADATEFORMAT': 'YYYYPT'}, last_year + last_period)

    first_date = datetime.datetime(
        int(first_year), first_month, start_day.day, 0, 0, 0)

    last_date = datetime.datetime(
        int(last_year), last_month, end_day.day, 23, 59, 59)

    # Currently not working but trying to set the step to source timestep.
    # p = QgsProjectTimeSettings()
    # p.setTimeStepUnit(10)

    # Display the temporal controller panel
    for i in iface.mainWindow().findChildren(QtWidgets.QDockWidget):
        if i.objectName() == 'Temporal Controller':
            i.setVisible(True)

    temporalNavigationObject = iface.mapCanvas().temporalController()
    temporalNavigationObject.setTemporalExtents(
        QgsDateTimeRange(first_date, last_date))
    temporalNavigationObject.setNavigationMode(
        temporalNavigationObject.NavigationMode.Animated)
