# coding: utf-8

from django.conf import settings
from django.contrib.auth.models import Permission
from django.core.management.base import BaseCommand


def get_permissions(model, perms):

    return [
        Permission.objects.get_by_natural_key(
            '%s_%s' % (perm, model), 'api', model
        )
        for perm in perms
    ]


def get_perms(perms):

    if not perms:
        return '!!(крас)нет доступа!!'

    output = settings.PERM_DISPLAY_NAMES.get(perms, None)

    if output is not None:
        return output

    output = '---'.join([settings.PERM_DISPLAY_NAMES[perm] for perm in perms])

    if output:
        return output

    return '!!(крас)нет доступа!!'


class Command(BaseCommand):
    help = ''

    def add_arguments(self, parser):
        pass

    def handle(self, *args, **options):

        table = []

        # Header row
        row = [info['meta']['name']['ru'] for info in settings.ROLES.values()]
        table.append(['-'] + row)

        for model, name in settings.MODEL_DISPLAY_NAMES.items():

            row = [name]

            for info in settings.ROLES.values():

                perms = dict(info['permissions']).get(model, None)
                row.append(get_perms(perms))

            table.append(row)

        print('#|')

        for i, row in enumerate(table):
            if i == 0:
                print('**', end='')

            print('||', end='')
            print('|'.join(row), end='')

            print('||', end='')
            if i == 0:
                print('**', end='')
            print()

        print('|#')
