import phonenumbers
from django.core.validators import ValidationError


class PhoneValidator(object):
    default_country_code = 'RU'

    def __init__(self, country_code=None):
        self.country_code = country_code or self.default_country_code

    def __call__(self, value):
        try:
            parsed = phonenumbers.parse(value, self.country_code)
        except phonenumbers.NumberParseException as ex:
            raise ValidationError(str(ex), code='invalid')

        if not phonenumbers.is_valid_number(parsed):
            raise ValidationError('Phone number is invalid', code='invalid')

        if not phonenumbers.is_possible_number(parsed):
            raise ValidationError('Phone number is impossible', code='invalid')


validate_phone = PhoneValidator()


def phone_is_valid(number):
    try:
        validate_phone(number)
        return True
    except ValidationError:
        return False
