# -*- 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, display_current=True,
                 parent=None):
        super(Plot, self).__init__(
            canvas=canvas,
            trad=trad,
            data=data,
            toolbar=toolbar,
            parent=parent
        )

        self._display_current = display_current

        self.line_kp_zmin = None
        self.line_kp_sl = []

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

        self.canvas.axes.axes.get_xaxis().set_visible(False)
        self.canvas.axes.set_ylabel(
            self._trad["height"],
            color='green', fontsize=10
        )

        if self.data is None:
            return

        x = [0, 1]
        z = [0, 0]
        sl = self.data.height()
        names = ["bottom"] + self.data.names()

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

        lsl = []
        for i in range(len(sl)):
            cur = []
            for _ in x:
                cur.append(sl[i])
            lsl.append(cur)

        # Compute sediment layer in function to point z
        z_sl = reduce(
            lambda acc, v: acc + [
                list(
                    map(lambda x, y: y - x, v, acc[-1])
                )
            ],
            lsl,
            [z]
        )

        for i, zsl in enumerate(reversed(z_sl)):
            self.line_kp_sl.append(None)
            self.line_kp_sl[i], = self.canvas.axes.plot(
                x, zsl,
                label=names[-(i+1)],
                linestyle="solid" if i == len(names) - 1 else "--",
                lw=1.8,
                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)]}')

        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 None:
            logger.info("TODO: Update")

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