from django.core.management.base import BaseCommand
from django.db import connections
from django.utils.text import slugify
from establishment.management.commands.add_position import namedtuplefetchall
from main.models import SiteSettings, Feature, SiteFeature
from location.models import Country
from tqdm import tqdm


class Command(BaseCommand):
    help = '''Add site_features for old db to new db.
    Run after command add_site_settings!'''

    def site_sql(self):
        with connections['legacy'].cursor() as cursor:
            cursor.execute('''
                            select s.id, s.country_code_2
                            from sites as s               
                           ''')
            return namedtuplefetchall(cursor)

    def update_site_old_id(self):
        for a in tqdm(self.site_sql(), desc='Update old_id site: '):
            country = Country.objects.filter(code=a.country_code_2).first()
            SiteSettings.objects.filter(country=country, old_id__isnull=True)\
                .update(old_id=a.id)
        self.stdout.write(self.style.WARNING(f'Updated old_id site.'))

    def feature_sql(self):
        with connections['legacy'].cursor() as cursor:
            cursor.execute('''
                            select f.id, slug 
                            from features as f 
                           ''')
            return namedtuplefetchall(cursor)

    def add_feature(self):
        objects = []
        for a in tqdm(self.feature_sql(), desc='Add feature: '):
            features = Feature.objects.filter(slug=slugify(a.slug)).update(old_id=a.id)
            if features == 0:
                objects.append(
                    Feature(slug=slugify(a.slug), old_id=a.id)
                )
        Feature.objects.bulk_create(objects)
        self.stdout.write(self.style.WARNING(f'Created feature objects.'))

    def site_features_sql(self):
        with connections['legacy'].cursor() as cursor:
            cursor.execute('''
                                select s.id as old_site_feature,  
                                       s.site_id, 
                                       case when s.state = 'published' 
                                        then True 
                                        else False 
                                       end as published,
                                       s.feature_id, 
                                       c.country_code_2
                                from features as f 
                                join site_features s on s.feature_id=f.id 
                                join sites c on c.id = s.site_id
                           ''')
            return namedtuplefetchall(cursor)

    def add_site_features(self):
        objects = []
        for a in tqdm(self.site_features_sql(), desc='Add site feature: '):
            site = SiteSettings.objects.get(old_id=a.site_id,
                                            subdomain=a.country_code_2)
            feature = Feature.objects.get(old_id=a.feature_id)

            site_features = SiteFeature.objects\
                .filter(site_settings=site,
                        feature=feature
                        ).update(old_id=a.old_site_feature, published=a.published)

            if site_features == 0:
                objects.append(
                    SiteFeature(site_settings=site,
                                feature=feature,
                                published=a.published,
                                main=False,
                                old_id=a.old_site_feature
                                )
                )
        SiteFeature.objects.bulk_create(objects)
        self.stdout.write(self.style.WARNING(f'Site feature add objects.'))

    def handle(self, *args, **kwargs):
        self.update_site_old_id()
        self.add_feature()
        self.add_site_features()


