#!/usr/bin/env python3
"""
UDP broadcast для обнаружения устройства
"""

import socket
import time
import threading
from datetime import datetime


class UDPBroadcast:
    def __init__(self, port: int = 48899, interval: int = 5, device_name: str = "SamovarichLogger", mask: str = "255.255.255.255"):
        self.port = port
        self.interval = interval
        self.device_name = device_name
        self.running = False
        self.sock = None
        self.mask = mask
    
    def start(self):
        self.running = True
        
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            self.sock.settimeout(1.0)
            
            print(f"UDP broadcast запущен на порту {self.port}")
            
            flip = True
            
            while self.running:
                try:
                    if flip:
                        message = self.device_name
                    else:
                        epoch_time = int(time.time())
                        message = f"EpochTime:{epoch_time}"
                    
                    self.sock.sendto(message.encode(), (self.mask, self.port))
                    flip = not flip
                    
                    for _ in range(self.interval * 10):
                        if not self.running:
                            break
                        time.sleep(0.1)
                        
                except socket.timeout:
                    continue
                except Exception:
                    time.sleep(1)
                    
        except Exception as e:
            print(f"UDP broadcast ошибка: {e}")
        finally:
            self.stop()
    
    def stop(self):
        self.running = False
        if self.sock:
            try:
                self.sock.close()
            except:
                pass
        print("UDP broadcast остановлен")