# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-08-20 20:20
from __future__ import unicode_literals

import datetime

from django.conf import settings
from django.db import migrations

from nokia import NokiaAuth

from nokiaapp.utils import get_setting


def migrate_to_oauth2(apps, schema_editor):
    NokiaUser = apps.get_model("nokiaapp", "NokiaUser")
    auth = NokiaAuth(
        get_setting('NOKIA_CLIENT_ID'), get_setting('NOKIA_CONSUMER_SECRET'))
    for user in NokiaUser.objects.all():
        try:
            token = auth.migrate_from_oauth1(
                user.access_token,
                user.access_token_secret
            )
            user.access_token = token['access_token']
            user.token_expiry = int((
                datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)
            ).total_seconds()) + int(token['expires_in'])
            user.token_type = token['token_type']
            user.refresh_token = token['refresh_token']
            user.save()
        except:
            # Problem with existing token
            user.delete()


class Migration(migrations.Migration):

    dependencies = [
        ('nokiaapp', '0004_add_oauth2_fields'),
    ]

    operations = [
        migrations.RunPython(migrate_to_oauth2, migrations.RunPython.noop),
    ]
