"""
Set the credit line shown at the foot of every public page.

New installs get this from `ft_tenant_init` during install. This command is
for the ones that already existed, and for correcting a credit later.

Each install has its own database, so it runs per install:

    venv/bin/python manage.py set_builder_credit \\
      --name "Designed & Developed by Example.com" \\
      --url https://example.com \\
      --settings=config.settings.production

Nothing is hardcoded here on purpose. This file ships inside the blank
template, and a template that knows a company name stops being blank.
"""
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = 'Write the sub footer builder credit into this install\'s Settings.'

    def add_arguments(self, parser):
        parser.add_argument('--name', default='', help='The text, e.g. "Designed & Developed by Example.com".')
        parser.add_argument('--url', default='', help='Where it links to. Opens in a new tab.')
        parser.add_argument('--clear', action='store_true', help='Remove the credit from this install.')
        parser.add_argument('--show', action='store_true', help='Print what is set and change nothing.')

    def handle(self, *args, **options):
        from apps.pages.models import SiteSettings
        from apps.tenants.models import Tenant

        tenant = Tenant.objects.filter(is_master=True).first()
        if tenant is None:
            self.stderr.write(
                'No master tenant on this install, so there is no Settings row to write to. '
                'Run ft_tenant_init first.'
            )
            return

        row = SiteSettings.load(tenant)

        if options['show']:
            self.stdout.write(f'  tenant : {tenant.name}')
            self.stdout.write(f'  name   : {row.builder_name or "(not set)"}')
            self.stdout.write(f'  url    : {row.builder_url or "(not set)"}')
            return

        if options['clear']:
            row.builder_name = ''
            row.builder_url = ''
            row.save(update_fields=['builder_name', 'builder_url'])
            self.stdout.write(self.style.SUCCESS(f'Credit removed from {tenant.name}.'))
            return

        if not options['name'] or not options['url']:
            # Both or neither. A name with no link is not clickable, and a link
            # with no name renders an empty line, and the template hides the
            # block unless it has both.
            self.stderr.write('Both --name and --url are required. Use --clear to remove.')
            return

        row.builder_name = options['name']
        row.builder_url = options['url']
        row.save(update_fields=['builder_name', 'builder_url'])
        self.stdout.write(self.style.SUCCESS(
            f'{tenant.name}: "{row.builder_name}" linking to {row.builder_url}'
        ))
