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

from PyQt5.QtCore import (
    QCoreApplication
)

_translate = QCoreApplication.translate

logger = logging.getLogger()


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

        self.display_current = display_current

        self.line_xy = []
        self.line_gl = []

        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)

        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", "X (m)"),
            color='green', fontsize=10
        )
        self.canvas.axes.set_ylabel(
            _translate("Results", "Y (m)"),
            color='green', fontsize=10
        )
        self.canvas.axes.axis("equal")

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

        # Draw line for each profile
        self.line_xy = [
            self.canvas.axes.plot(
                x, y, lw=1.,
                color='b' if kp_min <= kp <= kp_max else 'grey',
                markersize=3, marker='+'
            )
            for x, y, kp in zip(
                reach.geometry.get_x(),
                reach.geometry.get_y(),
                kp
            )
        ]

        # Guide lines
        x_complete = reach.geometry.get_guidelines_x()
        y_complete = reach.geometry.get_guidelines_y()

        self.line_gl = [
            self.canvas.axes.plot(
                x, y,
            )
            for x, y in zip(x_complete, y_complete)
        ]

        if self.display_current:
            # Current profile
            profile = reach.profile(self._current_profile_id).geometry

            self.plot_selected, = self.canvas.axes.plot(
                profile.x(),
                profile.y(),
                lw=1., markersize=3,
                marker='+', color="b"
            )
            self.plot_selected.set_visible(False)

        # Display point under water
        poly_l_x = []
        poly_l_y = []
        poly_r_x = []
        poly_r_y = []
        for profile in reach.profiles:
            water_z = profile.get_ts_key(
                self._current_timestamp, "Z"
            )
            pgeo = profile.geometry

            x, y = reduce(
                lambda acc, pts: (acc[0] + [pts.x], acc[1] + [pts.y]),
                filter(
                    lambda pts: pts.z < water_z,
                    pgeo.points
                ),
                ([], [])
            )

            poly_l_x.append(x[0])
            poly_l_y.append(y[0])
            poly_r_x.append(x[-1])
            poly_r_y.append(y[-1])

            self.canvas.axes.plot(
                x, y, lw=1.,
                color='b',
                markersize=1,
                marker='o'
            )

        poly_x = poly_l_x + list(reversed(poly_r_x)) + [poly_l_x[0]]
        poly_y = poly_l_y + list(reversed(poly_r_y)) + [poly_l_y[0]]

        self.canvas.axes.fill(poly_x, poly_y, color='blue', alpha=1)

        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()
