"""Pandas utilities."""


def _setup():
    import logging
    import time
    import fcntl
    import struct
    import termios
    import threading

    class PandasResizer(threading.Thread):
        """Pandas width/max_row resizer depending on tty size."""

        def __init__(self, max_rows=200):
            self.max_rows = max_rows
            self.width = None
            self.logger = logging.getLogger("startup.pandas")
            self._run = False
            super().__init__(name=type(self).__name__, daemon=True)

        @staticmethod
        def _size():
            ioctl = fcntl.ioctl(
                0, termios.TIOCGWINSZ, struct.pack("HHHH", 0, 0, 0, 0)
            )
            th, tw, hp, wp = struct.unpack("HHHH", ioctl)
            return tw, th

        def run(self):
            last_resize = float("inf")
            first_print = True
            self.logger.info("Resizer running")
            self._run = True
            while self._run:
                width = self._size()[0] - 1
                if width != self.width:
                    last_resize = time.time()
                    self.width = width
                if first_print or last_resize + 0.5 < time.time():
                    last_resize = float("inf")
                    pd.set_option("display.width", self.width)
                    pd.set_option("display.max_rows", self.max_rows)
                    if first_print:
                        self.logger.info(
                            "Resized pandas to %dx%d",
                            self.width,
                            self.max_rows,
                        )
                        first_print = False
                time.sleep(0.2)

        def stop(self):
            self._run = False

    PandasResizer().start()


try:
    import pandas as pd
    import numpy as np
except ModuleNotFoundError:
    pass
else:
    _setup()


del _setup

_summarise_startup()