from datetime import datetime, timedelta

defaults = {
    'infobeamer-cms': {
        'config': {
            'MAX_UPLOADS': 5,
            'PREFERRED_URL_SCHEME': 'https',
            'SESSION_COOKIE_NAME': '__Host-sess',
            'STATIC_PATH': '/opt/infobeamer-cms/static',
            'URL_KEY': repo.vault.password_for(f'{node.name} infobeamer-cms url key'),
            'VERSION': 1,
        },
        'workers': 4,
    },
}

@metadata_reactor.provides(
    'nginx/vhosts',
)
def nginx(metadata):
    if not node.has_bundle('nginx'):
        raise DoNotRunAgain

    return {
        'nginx': {
            'vhosts': {
                'infobeamer-cms': {
                    'domain': node.metadata.get('infobeamer-cms/domain'),
                    'locations': {
                        '/': {
                            'target': 'http://127.0.0.1:8000',
                        },
                        '/static': {
                            'alias': '/opt/infobeamer-cms/static',
                        },
                    },
                    'website_check_path': '/',
                    'website_check_string': 'Share your projects',
                    'do_not_set_content_security_headers': True,
                },
            },
        },
    }


@metadata_reactor.provides(
    'infobeamer-cms/config/DOMAIN',
    'infobeamer-cms/config/TIME_MAX',
    'infobeamer-cms/config/TIME_MIN',
)
def event_times(metadata):
    event_start = datetime.strptime(metadata.get('infobeamer-cms/event_start_date'), '%Y-%m-%d')
    event_duration = metadata.get('infobeamer-cms/event_duration_days', 4)

    event_end = event_start + timedelta(days=event_duration)

    return {
        'infobeamer-cms': {
            'config': {
                'DOMAIN': metadata.get('infobeamer-cms/domain'),
                'TIME_MAX': int(event_end.timestamp()),
                'TIME_MIN': int(event_start.timestamp()),
            },
        },
    }