# Plot.py -- Pamhyr
# Copyright (C) 2024-2025  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 tools import timer
from View.Tools.PamhyrPlot import PamhyrPlot

from PyQt5.QtCore import (
    QCoreApplication
)

_translate = QCoreApplication.translate

logger = logging.getLogger()


class Plot(PamhyrPlot):
    def __init__(self, data=None, canvas=None, trad=None,
                 toolbar=None, parent=None):
        super(Plot, self).__init__(
            canvas=canvas,
            trad=trad,
            data=data,
            toolbar=toolbar,
            parent=parent
        )

        self.label_x = self._trad["rk"]
        self.label_y = self._trad["elevation"]

        self.line_rk_zmin = None
        self.line_rk_sl = []

        self._isometric_axis = False

        self._auto_relim = False
        self._auto_relim_update = False
        self._autoscale_update = False

    @timer
    def draw(self):
        self.init_axes()

        if self.data is None:
            return

        if self.data.number_profiles == 0:
            return

        self.draw_data()

        self.idle()
        self._init = True

    def draw_data(self):
        rk = self.data.get_rk()
        sl = self.data.get_sl()
        z_min = self.data.get_z_min()

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

        z_sl = reduce(
            lambda acc, current_sl: acc + [
                list(
                    map(
                        lambda cur_sl_h, prev_sl_h: prev_sl_h - cur_sl_h,
                        current_sl, acc[-1]
                    )
                )
            ],
            sl,
            [z_min]
        )

        for i, z in enumerate(reversed(z_sl)):
            self.line_rk_sl.append(None)
            self.line_rk_sl[i], = self.canvas.axes.plot(
                rk, z,
                linestyle="solid" if i == len(z_sl) - 1 else "--",
                lw=1.5,
                color='grey' if i == len(z_sl) - 1 else None
            )

    @timer
    def update(self):
        self.draw()
