import os
import json
import subprocess
from datetime import datetime
from tqdm import tqdm
from django.core.management.base import BaseCommand
from module_iam.iam_fixture_script import IAMPrincipalType, IAMActions, IAMResources, IAMPrincipalSource


class Command(BaseCommand):
    help = "Load IAM fixtures data"

    def handle(self, *args, **options):
        app_name = "module_iam"
        try:
            self.stdout.write(self.style.SUCCESS("IAM fixtures data loading started..."))

            # Ensure the fixture directory exists
            fixture_directory = os.path.join(app_name, "fixtures")
            if not os.path.exists(fixture_directory):
                os.makedirs(fixture_directory)

            # Generate IAM category fixture data
            principal_type_fixture_data = IAMPrincipalType.create_iam_principal_type_fixture_data()

            # Specify the app name and fixture filename for category fixtures
            categories_fixture_filename = os.path.join(fixture_directory, "iam_principal_type_fixture.json")

            principal_type_fixture_data_list = []
            with tqdm(total=len(principal_type_fixture_data), desc="Loading IAM principal type fixture") as pbar:
                for item in principal_type_fixture_data:
                    principal_type_fixture_data_list.append(item)
                    pbar.update(1)

            # Dump category fixture data as JSON
            with open(categories_fixture_filename, "w") as fixture_file:
                json.dump(principal_type_fixture_data, fixture_file, indent=4)

            self.stdout.write(
                self.style.SUCCESS(f"IAM category fixture data has been loaded successfully. Fixture file location: {categories_fixture_filename}")
            )

            principal_source_fixture_data = IAMPrincipalSource.create_iam_principal_source_fixture_data()

            # Specify the app name and fixture filename for source fixtures
            source_fixture_filename = os.path.join(fixture_directory, "iam_principal_source_fixture.json")

            principal_source_fixture_data_list = []
            with tqdm(total=len(principal_source_fixture_data), desc="Loading IAM principal source fixture") as pbar:
                for item in principal_source_fixture_data:
                    principal_source_fixture_data_list.append(item)
                    pbar.update(1)

            # Dump category fixture data as JSON
            with open(source_fixture_filename, "w") as fixture_file:
                json.dump(principal_source_fixture_data, fixture_file, indent=4)

            self.stdout.write(
                self.style.SUCCESS(f"IAM category fixture data has been loaded successfully. Fixture file location: {categories_fixture_filename}")
            )

            # Generate IAM action fixture data
            action_fixture_data = IAMActions.create_iam_action_fixture_data()

            # Specify the fixture filename for action fixtures
            action_fixture_filename = os.path.join(fixture_directory, "iam_actions_fixture.json")

            action_fixture_data_list = []
            with tqdm(total=len(action_fixture_data), desc="Loading IAM action fixture") as pbar:
                for item in action_fixture_data:
                    action_fixture_data_list.append(item)
                    pbar.update(1)

            # Dump action fixture data as JSON
            with open(action_fixture_filename, "w") as fixture_file:
                json.dump(action_fixture_data, fixture_file, indent=4)

            self.stdout.write(
                self.style.SUCCESS(f"IAM action fixture data has been loaded successfully. Fixture file location: {action_fixture_filename}")
            )

            # Generate IAM resource fixture data
            resource_fixture_data = IAMResources.create_iam_resource_fixture_data()

            # Specify the fixture filename for resource fixtures
            resource_fixture_filename = os.path.join(fixture_directory, "iam_resources_fixture.json")

            resource_fixture_data_list = []
            with tqdm(total=len(resource_fixture_data), desc="Loading IAM resource fixture") as pbar:
                for item in resource_fixture_data:
                    resource_fixture_data_list.append(item)
                    pbar.update(1)

            # Dump resource fixture data as JSON
            with open(resource_fixture_filename, "w") as fixture_file:
                json.dump(resource_fixture_data, fixture_file, indent=4)

            self.stdout.write(
                self.style.SUCCESS(f"IAM resource fixture data has been loaded successfully. Fixture file location: {resource_fixture_filename}")
            )

            # Run the loaddata command to load the created fixtures
            loaddata_command_categories = f"python manage.py loaddata {categories_fixture_filename}"
            subprocess.run(loaddata_command_categories, shell=True)

            loaddata_command_categories = f"python manage.py loaddata {source_fixture_filename}"
            subprocess.run(loaddata_command_categories, shell=True)

            loaddata_command_actions = f"python manage.py loaddata {action_fixture_filename}"
            subprocess.run(loaddata_command_actions, shell=True)

            loaddata_command_resources = f"python manage.py loaddata {resource_fixture_filename}"
            subprocess.run(loaddata_command_resources, shell=True)

            self.stdout.write(
                self.style.SUCCESS("IAM fixtures data loading completed successfully.")
            )
        except Exception as e:
            # Handle exceptions here
            self.stderr.write(
                self.style.ERROR(f"IAM fixtures data loading failed: {str(e)}")
            )