import time

import pyqtgraph as pg
from IPython import embed
import numpy as np
from pyqtgraph.Qt.QtCore import QTimer

from pyrelacs.dataio.circbuffer import CircBuffer
from pyrelacs.util.logging import config_logging

log = config_logging()


class Continously:
    def __init__(self, figure: pg.GraphicsLayoutWidget, buffer: CircBuffer):
        self.figure = figure
        self.buffer = buffer

    def plot(self, *args, **kwargs):
        self.figure.setBackground("w")

        prev_plot = self.figure.getItem(row=0, col=0)
        if prev_plot:
            self.figure.removeItem(prev_plot)
        self.continous_ax = self.figure.addPlot(row=0, col=0)

        pen = pg.mkPen("red")
        self.time = np.zeros(self.buffer.size)
        self.data = np.empty(self.buffer.size)
        self.line = self.continous_ax.plot(
            self.time,
            self.data,
            pen=pen,
            # symbol="o",
        )

        # self.plot_index = 0
        self.timer = QTimer()
        self.CHUNK_PLOT = int(self.buffer.samplerate / 6)
        self.PLOT_HISTORY = 500_000  # The amount of data you want to keep on screen
        self.last_plotted_index = 0
        self.timer.setInterval(150)
        self.timer.timeout.connect(self.update_plot)
        self.timer.start()

    def update_plot(self):
        current_index = self.buffer.write_index()
        total_count = self.buffer.totalcount()

        start_time = time.time()
        if total_count - self.last_plotted_index >= self.CHUNK_PLOT:
            times, items = self.buffer.read(
                self.last_plotted_index,
                extend=self.CHUNK_PLOT,
            )

            self.time = np.concatenate((self.time, times))[-self.PLOT_HISTORY :]
            self.data = np.concatenate((self.data, items))[-self.PLOT_HISTORY :]
            self.line.setData(
                self.time,
                self.data,
            )
            self.last_plotted_index += self.CHUNK_PLOT
            end_time = time.time()
            log.debug(f"total time for plotting {end_time - start_time}")
        else:
            pass

    def stop_plotting(self):
        self.timer.stop()

    def refresh(self):
        self.continous_ax.enableAutoRange()