import os
import re

from config import *
import socket

def get_screen_centre():
    return (PROP_SCREEN_WIDTH * PROP_WINDOW_SCALE) / 2, (PROP_SCREEN_HEIGHT * PROP_WINDOW_SCALE) / 2


# noinspection PyTypeChecker
def color_hex_to_tuple(hx: str) -> tuple[int, int, int]:
    """
    Convert a 6-digit hex colour string to a tuple of RGB values.
    If a hash symbol is present, it is removed.
    :param hx: the hex colour string
    :return: the RGB tuple
    """
    hx = hx.removeprefix("#")
    return tuple(int(hx[i:i + 2], 16) for i in (0, 2, 4))


def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(0)
    try:
        # doesn't even have to be reachable
        s.connect(('10.254.254.254', 1))
        ip_addr = s.getsockname()[0]
    except Exception:
        ip_addr = '127.0.0.1'
    finally:
        s.close()
    return ip_addr

def get_font_path_or_default(pygame, font_name: str|None, bold=False, italic=False) -> str:
    if font_name is not None:
        if re.match(r".+\.ttf", font_name):
            if os.path.exists(font_name):
                font_path = font_name
            else:
                font_path = pygame.font.get_default_font()
        else:
            font_path = pygame.font.match_font(font_name, bold, italic)
    else:
        font_path = pygame.font.get_default_font()
    return font_path
