from django.utils import timezone
from rest_framework import serializers

"""Exports serializers interfaces as TypeScript interfaces"""

__serializers = set()

def interface_name(Serializer):
    return Serializer.__name__.replace('Serializer', 'Type')


def export_interface(Serializer) -> None:
    """Mark this serializer so that its interface will be exported"""
    if issubclass(Serializer, serializers.Serializer):
        __serializers.add(_key(Serializer))


def ts_exported(Serializer) -> bool:
    """Check if a serializer interface should be exported as TS"""
    return _key(Serializer) in __serializers


def _key(Serializer):
    return '.'.join([Serializer.__module__, Serializer.__name__])

def header(app, *middle):
    now = timezone.now().strftime('%Y-%m-%d %H:%M')
    tz = timezone.now().tzinfo

    header = [
        f' * Generated by RxDjango on {now} ({tz})',
    ] + [
        f' * {line}' for line in middle
    ]

    footer = [
        f' * To rebuild it, run:',
        f' *     ./manage.py makefrontend [{app}]',
    ]

    warning = 'DO NOT EDIT THIS FILE'
    # make it fancy

    length = max([len(line) for line in header])
    w_left = int((length - len(warning)) / 2)
    w_right = length - len(warning) - w_left - 1

    header = [
        line + ' ' * (length - len(line) + 1) + '*'
        for line in header
    ]
    header.append(
        ' *' + ' ' * w_left + warning + ' ' * w_right + '*',
    )

    footer = [
        line + ' ' * (length - len(line) + 1) + '*'
        for line in footer
    ]

    code = [
        '/*' + '*' * length
    ]
    for line in header:
        code.append(line)
        code.append(
            ' *' + ' ' * (length - 1) + '*',
        )

    for line in footer:
        code.append(line)
        code.append(
            ' *' + ' ' * (length - 1) + '*',
        )

    code.append(
        ' ' + '*' * length + '*/'
    )

    return code
