
import sys

from django.core.management.base import BaseCommand
from importer.ancestry import Ancestry
from cms.pages.models import BasePage

# some pages are autogenerated so for now lets ignore them

MOVE_PAGE_IGNORE = [
    'news-items-base',
    'blog-items-base',
    'atlas-case-study-items-base',
    'publication-items-base',
]

class Command(BaseCommand):
    
    """
    the purpose of this module is to move pages under the correct parent according to worpress.
    """

    help = 'Moves pages into position indicated by the parent field (the wordpress page id)'

    def handle(self, *args, **options):
        pages = BasePage.objects.all()

        if not pages:
            sys.stdout.write(
                '⚠️  Run `runimport pages` before running this command\n')
            sys.exit()

        for page in pages:
            if not page.slug in MOVE_PAGE_IGNORE:
                sys.stdout.write('\n⌛️ {} is moving'.format(page))
                
                parent_id = Ancestry(page).get_parent()
                if parent_id:
                    parent = BasePage.objects.get(id=parent_id)
                    page.move(parent, pos='last-child')
                    sys.stdout.write('\n✅ {} done'.format(page))
            
        sys.stdout.write('\n✅  All pages moved\n')
