# PlotH.py -- Pamhyr
# Copyright (C) 2023  INRAE
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# -*- coding: utf-8 -*-

import logging

from functools import reduce
from datetime import datetime

from tools import timer, trace
from View.Tools.PamhyrPlot import PamhyrPlot

from PyQt5.QtCore import (
    QCoreApplication
)

_translate = QCoreApplication.translate

logger = logging.getLogger()


class PlotH(PamhyrPlot):
    def __init__(self, canvas=None, trad=None, toolbar=None,
                 results=None, reach_id=0, profile_id=0,
                 parent=None):
        super(PlotH, self).__init__(
            canvas=canvas,
            trad=trad,
            data=results,
            toolbar=toolbar,
            parent=parent
        )

        self._mode = "time"

        self._current_timestamp = max(results.get("timestamps"))
        self._current_reach_id = reach_id
        self._current_profile_id = profile_id

    @property
    def results(self):
        return self.data

    @results.setter
    def results(self, results):
        self.data = results
        self._current_timestamp = max(results.get("timestamps"))

    @timer
    def draw(self, highlight=None):
        self.canvas.axes.cla()
        self.canvas.axes.grid(color='grey', linestyle='--', linewidth=0.5)

        if self.results is None:
            return

        reach = self.results.river.reach(self._current_reach_id)
        profile = reach.profile(self._current_profile_id)

        if reach.geometry.number_profiles == 0:
            self._init = False
            return

        kp_min, kp_max = (-1, -1)
        if highlight is not None:
            kp_min, kp_max = highlight

        # Axes
        self.canvas.axes.set_xlabel(
            _translate("Results", "Time (s)"),
            color='green', fontsize=10
        )
        self.canvas.axes.set_ylabel(
            _translate("Results", "Discharge (m³/s)"),
            color='green', fontsize=10
        )

        ts = list(self.results.get("timestamps"))
        ts.sort()

        self.canvas.axes.set_xlim(
            left=min(ts), right=max(ts)
        )

        # Draw discharge for each timestamp
        x = ts
        y = profile.get_key("Q")

        if len(ts) != len(x):
            logger.warning(
                "Results as less Q data ({len(x)}) " +
                "than timestamps ({len(ts)}) " +
                "for profile {self._current_profile_id}"
            )
            return

        self.canvas.axes.set_ylim(
            [min(min(y), 0), max(y) + 10]
        )

        self._line = [
            self.canvas.axes.plot(
                x, y, lw=1.,
                color='r',
                markersize=3, marker='+'
            )
        ]

        # Custom time display
        nb = len(x)
        mod = int(nb / 5)
        mod = mod if mod > 0 else nb

        fx = list(
            map(
                lambda x: x[1],
                filter(
                    lambda x: x[0] % mod == 0,
                    enumerate(x)
                )
            )
        )

        if self._mode == "time":
            t0 = datetime.fromtimestamp(0)
            xt = list(
                map(
                    lambda v: (
                        str(
                            datetime.fromtimestamp(v) - t0
                        ).split(",")[0]
                        .replace("days", _translate("Results", "days"))
                        .replace("day", _translate("Results", "day"))
                    ),
                    fx
                )
            )
        else:
            xt = list(
                map(
                    lambda v: str(datetime.fromtimestamp(v).date()),
                    fx
                )
            )

        self.canvas.axes.set_xticks(ticks=fx, labels=xt, rotation=45)

        # self.canvas.axes.autoscale_view(True, True, True)
        # self.canvas.axes.autoscale()
        self.canvas.figure.tight_layout()
        self.canvas.figure.canvas.draw_idle()
        if self.toolbar is not None:
            self.toolbar.update()

    def set_reach(self, reach_id):
        self._current_reach_id = reach_id
        self._current_profile_id = 0
        self.draw()

    def set_profile(self, profile_id):
        self._current_profile_id = profile_id
        self.draw()

    def set_timestamp(self, timestamp):
        self._current_timestamp = timestamp
        self.draw()

    def update(self):
        self.draw()
