# Plot.py -- Pamhyr
# Copyright (C) 2023-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 datetime import datetime

from tools import timer, trace
from View.Tools.PamhyrPlot import PamhyrPlot

from PyQt5.QtCore import (
    QCoreApplication
)

_translate = QCoreApplication.translate

logger = logging.getLogger()


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

        self._table_headers = self._trad.get_dict("table_headers")

        header = self.data.header
        self.label_x = self._table_headers[header[0]]
        self.label_y = self._table_headers[header[1]]

        self._mode = mode
        self._isometric_axis = False

        self._auto_relim_update = True
        self._autoscale_update = False

    def custom_ticks(self):
        if self.data.header[0] != "time":
            return

        self.set_ticks_time_formater()

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

        if len(self.data) == 0:
            self._init = False
            return

        self.draw_data()
        self.custom_ticks()

        self.idle()
        self._init = True

    def draw_data(self):
        # Plot data
        x = list(map(lambda v: v[0], self.data.data))
        y = list(map(lambda v: v[1], self.data.data))

        self._line, = self.canvas.axes.plot(
            x, y,
            color=self.color_plot,
            **self.plot_default_kargs
        )

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

        self.update_data()

        self.update_idle()

    def update_data(self):
        x = list(map(lambda v: v[0], self.data.data))
        y = list(map(lambda v: v[1], self.data.data))

        self._line.set_data(x, y)
