# coding=utf-8

from django.db import connection
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.contrib.sites.models import Site


class Command(BaseCommand):
  args = '<id_or_name>'
  help = 'Fix any broken article urls due to wrong root site id'

  def handle(self, *args, **options):
    id_or_name = args[0]

    try:
      site = Site.objects.get(id=int(id_or_name))
    except (Site.DoesNotExist, ValueError):
      try:
        site = Site.objects.get(domain=id_or_name)
      except Site.DoesNotExist:
        try:
          site = Site.objects.get(name=id_or_name)
        except Site.DoesNotExist:
          raise CommandError('No such site: %s' % id_or_name)

    root_site = site.settings.root_site

    # Remove any duplicate urls
    from begood.models import ArticleUrl
    on_new = ArticleUrl.objects.filter(article__sites=site).filter(site=root_site).values_list('article_id', flat=True)
    ArticleUrl.objects.filter(article_id__in=on_new).exclude(site=root_site).delete()

    # Update all urls to the new root site
    ArticleUrl.objects.filter(article__sites=site).update(site=site)


Add a management command to fix broken article urls when changing root site id.