import boto3
import json
import re
import collections
import datetime
import pytz

from params import Params


USERS_FOLDER = 'users/'
STATE_FOLDER = 'state/'


def getStateFilename(basename, ext, ord=None):
    name = ''.join((STATE_FOLDER, basename.lower(), '.', ext))
    if ord is not None:
        name = ''.join((name, '.', str(ord)))
    return name


def getUserFilename(user):
    return ''.join((USERS_FOLDER, user.lower()))


def getExpiryTime(max_age=None):
    return datetime.datetime.now(pytz.UTC) - \
        datetime.timedelta(
            seconds=Params.MAX_AGE if max_age is None else max_age)


def getFullHostname(host):
    return ''.join((host, '.', Params.DOMAIN_ROOT))


def getMaxErrors():
    return Params.MAX_ERRORS


def argToTuple(arg):
    if arg is None:
        return ()
    elif isinstance(arg, str):
        return (arg,)
    else:
        return tuple(arg)


def kickManager(session):
    if Params.DO_SNS:
        session.client('sns').publish(
            TopicArn=Params.SNS_ARN,
            Message='{"Event":"Change"}',
            )


'''
The tuple returned by S3Bucket.iterStateFiles()

file: The S3 ObjectSummary for the file
item: The base filename
host: If the file references a hostname, the name
user: If the file references a hostname, the user portion
sub:  If the file references a hostname, the option part
ip:   If the file references an IP, the IP
ord:  If the extension is followed by an integer ordinal, the value
'''
StateFile = collections.namedtuple(
    'StateFile', 'file item host user sub ip ext ord')

'''
The tuple returned by S3Bucket.iterUserFiles()

file: The S3 ObjectSummary for the file
user: The username
'''
UserFile = collections.namedtuple(
    'UserFile', 'file user')


class S3Bucket():
    PING_EXT = 'ping'
    HOLD_EXT = 'hold'
    EXPIRED_EXT = 'expired'
    ERROR_EXT = 'error'
    LOCK_EXT = 'lock'