from psycopg2 import sql

from django.apps import apps
from django.core.management.base import BaseCommand
from django.db import connection

QUERY_TEMPLATE = 'GRANT SELECT ON {} TO {};'


class Command(BaseCommand):
    def transfer_manager_grants(self, options):
        username = options['user']
        verbosity = options['verbosity']
        with connection.cursor() as cursor:
            for model in apps.get_models():
                if verbosity > 1:
                    self.stdout.write(QUERY_TEMPLATE.format(model._meta.db_table, username))
                cursor.execute(
                    sql.SQL(QUERY_TEMPLATE).format(
                        sql.Identifier(model._meta.db_table),
                        sql.Identifier(username),
                    )
                )
                for m2m_field in model._meta.local_many_to_many:
                    if verbosity > 1:
                        self.stdout.write(QUERY_TEMPLATE.format(m2m_field.m2m_db_table(), username))
                    cursor.execute(
                        sql.SQL(QUERY_TEMPLATE).format(
                            sql.Identifier(m2m_field.m2m_db_table()),
                            sql.Identifier(username),
                        )
                    )

    def add_arguments(self, parser):
        parser.add_argument(
            '--user', dest='user', type=str,
            help='Transfer manager username', required=True,
        )

    def handle(self, *args, **options):
        self.stdout.write("Grant access on tables to transfer manager\n")
        self.transfer_manager_grants(options)
        self.stdout.write("Done\n")
