# 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

logger = logging.getLogger()


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

        self.label_x = ""
        self.canvas.axes.axes.get_xaxis().set_visible(False)

        self.label_y = self._trad["height"]

        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

        self.draw_data()

        self.idle()
        self._init = True

    def draw_data(self):
        x = [0, 1]
        z = [0, 0]

        z_sl = self.data.compute_height_from_bottom(z)
        names = ["bottom"] + self.data.names()

        self.canvas.axes.set_xlim(*x)

        for i, zsl in enumerate(reversed(z_sl)):
            self.line_rk_sl.append(None)
            self.line_rk_sl[i], = self.canvas.axes.plot(
                x, zsl,
                label=names[-(i+1)],
                linestyle="solid" if i == len(names) - 1 else "--",
                lw=1.5,
                color='grey' if i == len(names) - 1 else None
            )
            self.canvas.axes.text(
                x[0] + 0.01, zsl[0] + 0.01,
                f'{names[-(i+1)]}'
            )

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