# Generated by Django 2.2.28 on 2022-04-12 13:16
import redis
from django.db import migrations


def forwards_func(apps, schema_editor):
    RedisServer = apps.get_model('redisboard', 'RedisServer')
    db_alias = schema_editor.connection.alias
    for obj in RedisServer.objects.using(db_alias).all():
        if obj.hostname.startswith('/'):
            obj.url = f'unix://{obj.hostname}'
        else:
            obj.url = f'redis://{obj.hostname}:{obj.port}'
        obj.save(update_fields=['url'])


def reverse_func(apps, schema_editor):
    RedisServer = apps.get_model('redisboard', 'RedisServer')
    db_alias = schema_editor.connection.alias
    for obj in RedisServer.objects.using(db_alias).all():
        kwargs = redis.connection.parse_url(obj.url)
        if kwargs['connection_class'] is redis.UnixDomainSocketConnection:
            obj.hostname = kwargs['path']
            obj.save(update_fields=['hostname'])
        else:
            obj.hostname = kwargs['hostname']
            obj.port = kwargs['port']
            obj.save(update_fields=['hostname', 'port'])


class Migration(migrations.Migration):
    dependencies = [
        ('redisboard', '0002_add_url'),
    ]

    operations = [
        migrations.RunPython(forwards_func, reverse_func),
    ]
