from django.core.management.base import BaseCommand
from establishment.models import Establishment
from location.models import Country, Language
from transfer.models import Collections
from collection.models import Collection
from django.conf import settings
from news.models import News


class Command(BaseCommand):
    help = 'Import collection'

    def handle(self, *args, **kwargs):
        raw_qs = Collections.objects.raw('''
                                            select
                                            distinct
                                                 a.id,
                                                 a.collection_id,
                                            -- 	 a.establishment_id,
                                                 a.title,
                                                 a.tag_name,
                                                 a.slug,
                                            -- 	 a.attachment_file_name,
                                            -- 	 a.attachment_content_type,
                                            -- 	 a.attachment_file_size,
                                             	 a.attachment_suffix_url,
                                            -- 	 active as  is_publish,
                                                 a.country_code,
                                            --      a.geometries,
                                             	 a.description,
                                                 min(a.start) AS start
                                            from
                                            (
                                                select distinct
                                                       c.id,
                                                       c.id as collection_id,
                                                       m.establishment_id,
                                                       c.title, c.tag_name,
                                                       c.slug, c.attachment_file_name,
                                                       c.attachment_content_type, c.attachment_file_size,
                                                       c.attachment_suffix_url,
                                                       active,
                                                       s.country_code_2 as country_code,
                                                       c.geometries,
                                                       c.title as description,
                                                       m.created_at as start
                                                from collections as c
                                                join metadata m on m.value = c.tag_name
                                                join establishments  e on e.id = m.establishment_id
                                                join sites s  on s.id = c.site_id
                                                where m.`key` = 'collection'

                                                union

                                                select distinct
                                                       c.id,
                                                       c.id as collection_id,
                                                       m.establishment_id,
                                                       c.title, c.tag_name,
                                                       c.slug, c.attachment_file_name,
                                                       c.attachment_content_type, c.attachment_file_size,
                                                       c.attachment_suffix_url,
                                                       active,
                                                       s.country_code_2 as country_code,
                                                       c.geometries,
                                                       c.title as description,
                                                       m.created_at as start
                                                from collections as c
                                                join metadata m on m.value = c.slug
                                                join establishments  e on e.id = m.establishment_id
                                                join sites s  on s.id = c.site_id
                                                where m.`key` = 'collection'
                                            ) a
                                            group by
                                                 a.id,
                                                 a.collection_id,
                                            -- 	 a.establishment_id,
                                                 a.title,
                                                 a.tag_name,
                                                 a.slug,
                                            -- 	 a.attachment_file_name,
                                            -- 	 a.attachment_content_type,
                                            -- 	 a.attachment_file_size,
                                             	 a.attachment_suffix_url,
                                            -- 	 active as  is_publish,
                                                 a.country_code,
                                                 a.description
                                        ''')
        objects = []
        queryset = [vars(query) for query in raw_qs]
        for obj in queryset:
            # establishment = Establishment.objects.filter(old_id=obj['establishment_id']).first()
            # lang = Language.objects.filter(locale=obj['country_code'])
            country = Country.objects.filter(code=obj['country_code']).first()
            if country:
                objects.append(
                    Collection(name={settings.FALLBACK_LOCALE: obj['title']},
                               collection_type=Collection.POP if obj['description'].lower().find('pop') != -1
                                                              else Collection.ORDINARY,
                               country=country,
                               description={settings.FALLBACK_LOCALE: obj['description']},
                               slug=obj['slug'], old_id=obj['collection_id'],
                               start=obj['start'],
                               image_url='https://s3.eu-central-1.amazonaws.com/gm-test.com/media/'+obj['attachment_suffix_url']
                               )
                )
        Collection.objects.bulk_create(objects)

        raw_qs = Collections.objects.raw('''
                                            select
                                            distinct
                                                 a.id,
                                                 a.collection_id,
                                                 a.establishment_id, 
                                                 a.active
                                            from
                                            (
                                                select distinct
                                                       c.id,
                                                       c.id as collection_id,
                                                       m.establishment_id,
                                                       c.title, c.tag_name,
                                                       c.slug, c.attachment_file_name,
                                                       c.attachment_content_type, c.attachment_file_size,
                                                       c.attachment_suffix_url,
                                                       active,
                                                       s.country_code_2 as country_code,
                                                       c.geometries,
                                                       c.title as description,
                                                       m.created_at as start
                                                from collections as c
                                                join metadata m on m.value = c.tag_name
                                                join establishments  e on e.id = m.establishment_id
                                                join sites s  on s.id = c.site_id
                                                where m.`key` = 'collection'

                                                union

                                                select distinct
                                                       c.id,
                                                       c.id as collection_id,
                                                       m.establishment_id,
                                                       c.title, c.tag_name,
                                                       c.slug, c.attachment_file_name,
                                                       c.attachment_content_type, c.attachment_file_size,
                                                       c.attachment_suffix_url,
                                                       active,
                                                       s.country_code_2 as country_code,
                                                       c.geometries,
                                                       c.title as description,
                                                       m.created_at as start
                                                from collections as c
                                                join metadata m on m.value = c.slug
                                                join establishments  e on e.id = m.establishment_id
                                                join sites s  on s.id = c.site_id
                                                where m.`key` = 'collection'
                                            ) a
        ''')

        queryset = [vars(query) for query in raw_qs]
        for obj in queryset:
            print('COLLECT_ID: {}'.format(obj['collection_id']))
            est = Establishment.objects.filter(old_id=obj['establishment_id'])
            if est.exists():
                inst = est.first()
                collect = Collection.objects.filter(old_id=obj['collection_id'])
                collect.update(is_publish=obj['active'])
                print(f'COLLECT COUNT {collect.count()}')
                inst.collections.add(*list(collect))
                # for c in collect:
                #     inst.collections.add(c)
                inst.save()
