#!/usr/bin/env python3

import os
import sys
import random

import pygame


class SpotDisplay:
    FRAMES = 5

    PATH = [
        *((8 * 1, 8 * i) for i in range(1, 4)),
        *((8 * i, 8 * 3) for i in range(2, 9)),
        *((8 * 8, 8 * i) for i in range(2, 0, -1)),
        *((8 * i, 8 * 1) for i in range(7, 1, -1)),
    ]

    def __init__(self, width: int, height: int, debug: bool = False):
        self.width = width
        self.height = height
        self.debug = debug

        pygame.init()
        if not self.debug:
            self.screen = pygame.Surface((self.width, self.height), flags=pygame.SRCALPHA, depth=32)
        else:
            self.screen = pygame.display.set_mode((self.width, self.height))

        self.clock = pygame.time.Clock()
        self.i = 0
        self.stop = None
        self.sleep = 0

    def display(self):
        while True:
            self.clock.tick(self.FRAMES)

            if self.sleep:
                self.sleep -= 1
                continue

            self.screen.fill((0, 0, 0, 120))
            pygame.draw.rect(self.screen, (0, 0, 0, 255), pygame.Rect(*self.PATH[self.i], 8, 8))
            self.i = (self.i + 1) % len(self.PATH)

            if self.stop == 0 or self.stop is None:
                if self.stop is not None:
                    self.sleep = 7 * self.FRAMES
                self.stop = random.randint(8 * self.FRAMES, 20 * self.FRAMES)
            self.stop -= 1

            if not self.debug:
                os.write(1, pygame.image.tostring(self.screen, "RGBA"))
            else:
                pygame.display.flip()


if __name__ == "__main__":
    try:
        Nx = int(sys.argv[1])  # Breite des Displays
        Ny = int(sys.argv[2])  # Höhe des Displays
        debug = False
    except IndexError:
        Nx, Ny = 80, 40
        debug = True

    SpotDisplay(Nx, Ny, debug).display()
