import re
from pathlib import Path

from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.utils.translation import gettext_lazy


def mac_address_validator(value):
    """ Validator for checking if entered value is correct MAC address.
    Valid MAC address formats for this validator are:
        1. String, separated with '-', e.g. '01-3A-4f-Ee-23-AF'
        2. String, separated with ':', e.g. '01:3E:4F:EE:23:af'
    :param value: value from source for validation
    :return: pass validation or raise validation error
    """
    validation_error_message = gettext_lazy('Incorrect format of MAC address')
    # Regex value, which will validate provided string
    mac_regex = '[0-9a-f]{2}([-:]?)[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$'
    if not re.match(mac_regex, value.lower()):
        raise ValidationError(message=validation_error_message)


def domain_or_ip_validator(value):
    """ Validator for checking if entered value is IP address or domain
    :param value: value from user
    :return: pass validation or raise validation error
    """
    validation_error_message = gettext_lazy('Please enter valid domain or IP address')
    validator = URLValidator()
    value_with_scheme = f'https://{value}'
    try:
        validator(value_with_scheme)
    except ValidationError:
        raise ValidationError(message=validation_error_message)


class ValidateFileExtension:
    """Custom file extension form validator"""

    def __init__(self, allowed_extensions):
        if allowed_extensions is not None:
            allowed_extensions = [allowed_extension.lower() for allowed_extension in allowed_extensions]
        self.allowed_extensions = allowed_extensions

    def __call__(self, value):
        self.extension = Path(value.name).suffix.lower()
        self.message = gettext_lazy(
            "File extension '{extension}' is not allowed. Allowed extensions are: '{allowed_extensions}'.").format(
            extension=self.extension, allowed_extensions=', '.join(self.allowed_extensions))
        if self.allowed_extensions is not None and self.extension not in self.allowed_extensions:
            raise ValidationError(self.message)
