#!/usr/bin/env python3
import sys
import traceback
from time import perf_counter

import pyqtgraph as pg
from pyqtgraph.Qt.QtCore import QTimer
from pyqtgraph.Qt.QtWidgets import QApplication, QGridLayout, QWidget

interval_ms = 250
statm_index = 0  # use 5 to limit showing size of data + stack


class App(QWidget):
    def __init__(self):
        super().__init__()
        # GUI SETUP
        self.layout = QGridLayout()
        self.setLayout(self.layout)
        # CHART SETUP
        self.plot_widget = pg.PlotWidget()
        self.plot_widget.enableAutoRange()
        self.layout.addWidget(self.plot_widget)
        self.plot_data = {"time": [], "size": []}
        self.plot = self.plot_widget.plot(*self.plot_data.values())
        # print(self.plot)
        # self.plot_widget.addItem(self.plot)
        # DATA SETUP
        self.pid = sys.argv[1]
        self.statm_file = f"/proc/{self.pid}/statm"
        # PERIODIC SETUP
        self.timer = QTimer()
        # self.timer.setSingleShot(True)
        self.timer.setInterval(interval_ms)
        self.timer.timeout.connect(self.add_data)
        self.start = perf_counter()
        self.timer.start()

    def add_data(self):
        try:
            with open(self.statm_file, "r") as f:
                statm = f.read()
            self.plot_data["time"].append(perf_counter() - self.start)
            statm = statm.split()
            self.plot_data["size"].append(int(statm[statm_index]))
            self.plot.setData(*self.plot_data.values())
        except Exception:
            traceback.print_exc()
        self.timer.start()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = App()
    window.show()
    sys.exit(app.exec_())
