# PlotKPC.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 tools import timer
from View.Tools.PamhyrPlot import PamhyrPlot

from PyQt5.QtCore import (
    QCoreApplication
)

_translate = QCoreApplication.translate

logger = logging.getLogger()


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

        self.display_current = display_current

        self.line_kp_zgl = []
        self.line_kp_zmin = None
        self.line_kp_zmin_zmax = None

        self.before_plot_selected = None
        self.plot_selected = None
        self.after_plot_selected = None

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

        if self.data is None:
            return

        if self.data.number_profiles == 0:
            return

        self.canvas.axes.set_xlabel(
            _translate("MainWindow_reach", "Kp (m)"),
            color='green', fontsize=10
        )
        self.canvas.axes.set_ylabel(
            _translate("MainWindow_reach", "Height (m)"),
            color='green', fontsize=10
        )

        kp = self.data.get_kp()
        z_min = self.data.get_z_min()
        z_max = self.data.get_z_max()

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

        self.line_kp_zmin_zmax = self.canvas.axes.vlines(
            x=kp,
            ymin=z_min, ymax=z_max,
            color='r',
            lw=1.
        )

        if highlight is not None:
            kp_min, kp_max = highlight

            indexes = list(
                map(
                    lambda x: x[0],
                    filter(
                        lambda x: kp_min <= x[1] <= kp_max,
                        enumerate(kp)
                    )
                )
            )

            def indexes_filter(data): return list(
                map(
                    lambda x: x[1],
                    filter(
                        lambda x: x[0] in indexes,
                        enumerate(data)
                    )
                )
            )

            ikp = indexes_filter(kp)
            imin = indexes_filter(z_min)
            imax = indexes_filter(z_max)

            self.line_kp_zmin_zmax = self.canvas.axes.vlines(
                x=ikp,
                ymin=imin, ymax=imax,
                color='b',
                lw=1.
            )

        if self.display_current:
            self.plot_selected, = self.canvas.axes.plot(
                (kp[0], kp[0]),
                (z_min[0], z_max[0]),
                color='b', lw=1.8
            )
            self.plot_selected.set_visible(False)

            self.before_plot_selected, = self.canvas.axes.plot(
                (kp[0], kp[0]),
                (z_min[0], z_max[0]),
                color='k', lw=1.6, linestyle='--'
            )
            self.before_plot_selected.set_visible(False)

            self.after_plot_selected, = self.canvas.axes.plot(
                (kp[0], kp[0]),
                (z_min[0], z_max[0]),
                color='m', lw=1.6, linestyle='--'
            )
            self.after_plot_selected.set_visible(False)

        kp = self.data.get_kp()
        self.line_kp_zgl = []
        for z in self.data.get_guidelines_z():
            # Is incomplete guideline?
            if len(z) != len(kp):
                continue

            self.line_kp_zgl.append(
                self.canvas.axes.plot(
                    kp, z, lw=1.
                )
            )

        self.line_kp_zmin, = self.canvas.axes.plot(
            kp, z_min,
            linestyle=":", lw=1.8,
            color='lightgrey'
        )

        self.canvas.figure.tight_layout()
        self.canvas.figure.canvas.draw_idle()
        if self.toolbar is not None:
            self.toolbar.update()

        self._init = True

    @timer
    def update(self, ind=None):
        if not self._init:
            self.draw()
            return

        if ind is not None:
            before = ind - 1
            after = ind + 1

            self.before_plot_selected.set_visible(False)
            self.plot_selected.set_visible(False)
            self.after_plot_selected.set_visible(False)

            if 0 <= before < self.data.number_profiles:
                kp_i = self.data.profile(before).kp
                z_min_i = self.data.profile(before).z_min()
                z_max_i = self.data.profile(before).z_max()

                self.before_plot_selected.set_data(
                    (kp_i, kp_i),
                    (z_min_i, z_max_i)
                )
                self.before_plot_selected.set_visible(True)

            if 0 <= ind < self.data.number_profiles:
                kp_i = self.data.profile(ind).kp
                z_min_i = self.data.profile(ind).z_min()
                z_max_i = self.data.profile(ind).z_max()

                self.plot_selected.set_data(
                    (kp_i, kp_i),
                    (z_min_i, z_max_i)
                )
                self.plot_selected.set_visible(True)

            if 0 <= after < self.data.number_profiles:
                kp_i = self.data.profile(after).kp
                z_min_i = self.data.profile(after).z_min()
                z_max_i = self.data.profile(after).z_max()

                self.after_plot_selected.set_data(
                    (kp_i, kp_i),
                    (z_min_i, z_max_i)
                )
                self.after_plot_selected.set_visible(True)

            self.canvas.figure.canvas.draw_idle()
        else:
            kp = self.data.get_kp()
            z_min = self.data.get_z_min()
            z_max = self.data.get_z_max()

            self.line_kp_zmin.set_data(kp, z_min)

            self.line_kp_zmin_zmax.remove()
            self.line_kp_zmin_zmax = self.canvas.axes.vlines(
                x=kp,
                ymin=z_min, ymax=z_max,
                color='r', lw=1.
            )

            z_complete = self.data.get_guidelines_z()
            try:
                for i in range(len(self.line_kp_zgl)):
                    self.line_kp_zgl[i][0].set_data(
                        kp, z_complete[i]
                    )
            except Exception as e:
                logger.warning(f"Failed to update graphic KPZ: {e}")

            self.canvas.axes.autoscale_view(True, True, True)
            self.canvas.figure.canvas.draw_idle()
