from crypt import crypt as _crypt
from string import ascii_letters as _ascii_letters, digits as _digits
from secrets import choice as _choice
from risotto.utils import multi_function as _multi_function


def sha512_crypt(password):
    salt = ''.join([_choice(_ascii_letters + _digits) for _ in range(8)])
    prefix = '$6$'
    return _crypt(password, prefix + salt)


@_multi_function
def calc_domains(domains):
    ret = []
    for domain in domains:
        ret.append(domain)
        ret.append(domain)
        ret.append(f'autoconfig.{domain}')
    return ret


@_multi_function
def calc_locations(domain, index):
    i = index//3
    if 3 * i == index:
        # divisible by three
        return '/autodiscover/autodiscover.xml'
    elif 3 * i + 1 == index:
        return '/.well-known/autoconfig/mail/config-v1.1.xml'
    return '/mail/config-v1.1.xml'


@_multi_function
def calc_well_known(index, dns, doms):
    if None in (dns, doms):
        return None
    i = index//3
    return f'https://{dns}/mail/{doms[i]}/autodiscover/autodiscover.xml'
