# 2020-11-21 @bdauvergne
# script to change AttributeDefinition's kind of phone and mobile user's attributes from string to phone_number

import sys

from django.db import connection
from django.db.transaction import atomic
from django.utils.timezone import now

from hobo.deploy.signals import notify_agents, tls
from hobo.profile.models import AttributeDefinition


fake = '--fake' in sys.argv

class Fake(Exception):
    pass

tenant_name = connection.tenant.domain_url

names = ['mobile', 'phone']
kind = 'phone_number'

qs = AttributeDefinition.objects.filter(name__in=names).exclude(kind=kind)

count = qs.count()
if count:
    old_values = list(qs.values_list('name', 'kind'))
    try:
        with atomic():
            qs.update(kind=kind, last_update_timestamp=now())
            print(tenant_name, ': Updated attributes %s to kind=%s' % (old_values, kind))
            tls.MUST_NOTIFY = True
            if fake:
                raise Fake
            notify_agents(None)
    except Fake:
        print('faked!')
