# -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2017-01-30 11:53
from __future__ import unicode_literals

from django.db import migrations
from django.db.models import Q


# https://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support
LEGAL_IMAGES = [
    '.apng',
    '.bmp',
    '.gif',
    '.ico',
    '.jpeg',
    '.jpg',
    '.png',
    '.svg',
    '.tiff',
    '.xbm',
]


def set_invalid_images_to_empty_string(model_class, field_name):
    # Case-insensitive list lookup: http://stackoverflow.com/a/21468646/904887
    q_filter = Q()
    for item in LEGAL_IMAGES:
        q_filter |= Q(**{'{}__iendswith'.format(field_name): item})
    queryset = model_class.objects.exclude(q_filter)
    queryset.update(**{field_name: ''})


def remove_non_images_from_company(apps, schema_editor):
    Company = apps.get_model('company', 'Company')
    # remove images that do not end in supported types
    set_invalid_images_to_empty_string(Company, 'logo')


def remove_non_images_from_case_study(apps, schema_editor):
    CompanyCaseStudy = apps.get_model('company', 'CompanyCaseStudy')
    # remove images that do not end in supported types
    set_invalid_images_to_empty_string(CompanyCaseStudy, 'image_one')
    set_invalid_images_to_empty_string(CompanyCaseStudy, 'image_two')
    set_invalid_images_to_empty_string(CompanyCaseStudy, 'image_three')


def noop(*args, **kwargs):
    return


class Migration(migrations.Migration):

    dependencies = [
        ('company', '0031_auto_20170121_1552'),
    ]

    operations = [
        migrations.RunPython(remove_non_images_from_company, noop),
        migrations.RunPython(remove_non_images_from_case_study, noop),
    ]
