from django.core.management.base import BaseCommand
from tqdm import tqdm

from account.models import User
from main.models import Panel, SiteSettings
from transfer.models import Panels


class Command(BaseCommand):
    help = '''Add panels from legacy DB.'''

    def handle(self, *args, **kwargs):
        objects = []
        deleted = 0
        panels_list = Panels.objects.filter(name__isnull=False)
        # remove existing panel
        exist_panel = Panel.objects.filter(old_id__isnull=False)
        if exist_panel.exists():
            deleted = exist_panel.count()
            exist_panel.delete()

        for old_panel in tqdm(panels_list, desc='Add panels'):
            site = SiteSettings.objects.filter(old_id=old_panel.site_id).first()
            user = User.objects.filter(old_id=old_panel.site_id).first()
            if site:
                new_panel = Panel(
                    old_id=old_panel.id,
                    user=user,
                    site=site,
                    name=old_panel.name,
                    display=old_panel.display,
                    description=old_panel.description,
                    query=old_panel.query,
                )
                objects.append(new_panel)
        Panel.objects.bulk_create(objects)
        self.stdout.write(
            self.style.WARNING(f'Created {len(objects)}/Deleted {deleted} footer objects.'))
