from django.core.management.base import BaseCommand

from establishment.models import Establishment, SocialChoice, SocialNetwork
from transfer.models import EstablishmentInfos


class Command(BaseCommand):
    help = 'Add social links values from old db to new db'

    def handle(self, *args, **kwargs):
        count = 0

        facebook, _ = SocialChoice.objects.get_or_create(title='facebook')
        twitter, _ = SocialChoice.objects.get_or_create(title='twitter')
        instagram, _ = SocialChoice.objects.get_or_create(title='instagram')

        queryset = EstablishmentInfos.objects.exclude(
            establishment_id__isnull=True
        ).values_list('id', 'establishment_id', 'facebook', 'twitter', 'instagram')

        for id, es_id, facebook_url, twitter_url, instagram_url in queryset:
            establishment = Establishment.objects.filter(old_id=es_id).first()
            if not establishment:
                continue

            if facebook_url:
                if 'facebook.com/' not in facebook_url:
                    facebook_url = 'https://www.facebook.com/' + facebook_url
                obj, _ = SocialNetwork.objects.get_or_create(
                    old_id=id,
                    establishment=establishment,
                    network=facebook,
                    url=facebook_url,
                )
                count += 1
            if twitter_url:
                if 'twitter.com/' not in twitter_url:
                    twitter_url = 'https://www.twitter.com/' + twitter_url
                obj, _ = SocialNetwork.objects.get_or_create(
                    old_id=id,
                    establishment=establishment,
                    network=twitter,
                    url=twitter_url,
                )
                count += 1
            if instagram_url:
                if 'instagram.com/' not in instagram_url:
                    instagram = 'https://www.instagram.com/' + instagram_url
                obj, _ = SocialNetwork.objects.get_or_create(
                    old_id=id,
                    establishment=establishment,
                    network=instagram,
                    url=instagram_url,
                )
                count += 1

        self.stdout.write(self.style.WARNING(f'Created/updated {count} objects.'))
