from django.core.management.base import BaseCommand

from topdownrbac.services.import_roles_as_yaml_service import RoleSyncService


class Command(BaseCommand):
    help = "Sync RBAC roles from YAML file"

    def add_arguments(self, parser):
        parser.add_argument("yaml_path", type=str)

    def handle(self, *args, **options):
        service = RoleSyncService(options["yaml_path"])
        deactivated_roles, role_updates = service.sync()
        if len(deactivated_roles) == 0:
            self.stdout.write(self.style.SUCCESS("No roles deactivated..."))
        else:
            self.stdout.write(self.style.WARNING(f"Deactivated {len(deactivated_roles)} roles:"))
            for role in deactivated_roles:
                self.stdout.write(role)

        if len(role_updates) == 0:
            self.stdout.write(self.style.SUCCESS("No roles created or updated..."))
        else:
            self.stdout.write(self.style.SUCCESS(f"{len(role_updates)} role updates:"))
            for role in role_updates:
                if role[4]:
                    self.stdout.write(self.style.SUCCESS(f"Reactivated role {role[0]}"))
                if role[3]:
                    self.stdout.write(self.style.SUCCESS(f"Created role {role[0]} with permissions:"))
                    for perm in role[1]:
                        self.stdout.write(f"{perm}")
                elif role[1] or role[2]:
                    self.stdout.write(self.style.SUCCESS(f"Updated role {role[0]}. Permissions changed:"))
                    for perm in role[1]:
                        self.stdout.write(f"+ {perm}")
                    for perm in role[2]:
                        self.stdout.write(f"- {perm}")
        self.stdout.write(self.style.SUCCESS("Default roles synced successfully !"))
