# Generated by Django 3.1 on 2021-01-19 12:08

from datetime import timedelta

from auth_token.config import settings
import auth_token.enums
import auth_token.models
from django.conf import settings as django_settings
import django.core.serializers.json
from django.db import migrations, models
from django.db.models import F
from django.utils.timezone import now
import django.db.models.deletion
from django.utils.crypto import salted_hmac
import enumfields.fields
from auth_token.utils import compute_expires_at, generate_key, hash_key


def migrate_tokens(apps, schema_editor):
    Token = apps.get_model('auth_token', 'Token')
    AuthorizationToken = apps.get_model('auth_token', 'AuthorizationToken')
    unexpired_active_token_qs = Token.objects.filter(
        is_active=True,
        last_access__gte=now() - timedelta(seconds=settings.DEFAULT_TOKEN_AGE)
    )
    for token in unexpired_active_token_qs:
        AuthorizationToken.objects.create(
            key=salted_hmac(
                settings.HASH_SALT,
                token.key,
                secret='|'.join(('', django_settings.SECRET_KEY)),
                algorithm=django_settings.DEFAULT_HASHING_ALGORITHM,
            ).hexdigest(),
            user=token.user,
            is_active=token.is_active,
            user_agent=token.user_agent,
            expires_at=token.last_access + timedelta(seconds=settings.DEFAULT_TOKEN_AGE),
            ip=token.ip,
            auth_slug=token.auth_slug,
            backend=token.backend,
            allowed_cookie=token.allowed_cookie,
            allowed_header=token.allowed_header,
            is_authenticated=token.is_authenticated,
            preserve_cookie=token.expiration,
            mobile_device=None,
            created_at=token.created_at,
            changed_at=token.last_access
        )


def set_mobile_device_changed_at(apps, schema_editor):
    MobileDevice = apps.get_model('auth_token', 'MobileDevice')
    MobileDevice.objects.filter(last_login__isnull=True).update(changed_at=F('created_at'))
    MobileDevice.objects.filter(last_login__isnull=False).update(changed_at=F('last_login'))


class Migration(migrations.Migration):
    dependencies = [
        migrations.swappable_dependency(django_settings.AUTH_USER_MODEL),
        ('contenttypes', '0002_remove_content_type_name'),
        ('auth_token', '0011_auto_20210119_1308'),
    ]

    operations = [
        migrations.RunPython(migrate_tokens),
        migrations.RunPython(set_mobile_device_changed_at),
    ]
