# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-04-27 09:11
from __future__ import unicode_literals

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models

import pretix.base.models.organizer


def create_teams(apps, schema_editor):
    Event = apps.get_model('pretixbase', 'Event')
    Organizer = apps.get_model('pretixbase', 'Organizer')
    Team = apps.get_model('pretixbase', 'Team')
    TeamInvite = apps.get_model('pretixbase', 'TeamInvite')
    EventPermission = apps.get_model('pretixbase', 'EventPermission')
    OrganizerPermission = apps.get_model('pretixbase', 'OrganizerPermission')

    for o in Organizer.objects.prefetch_related('events'):
        for e in o.events.all():
            teams = {}

            for p in e.user_perms.all():
                pkey = (p.can_change_settings, p.can_change_items, p.can_view_orders,
                        p.can_change_permissions, p.can_change_orders, p.can_view_vouchers,
                        p.can_change_vouchers)
                if pkey not in teams:
                    team = Team()
                    team.can_change_event_settings = p.can_change_settings
                    team.can_change_items = p.can_change_items
                    team.can_view_orders = p.can_view_orders
                    team.can_change_orders = p.can_change_orders
                    team.can_view_vouchers = p.can_view_vouchers
                    team.can_change_vouchers = p.can_change_vouchers
                    team.organizer = o
                    team.name = '{} Team {}'.format(
                        str(e.name), len(teams) + 1
                    )
                    team.save()
                    team.limit_events.add(e)

                    teams[pkey] = team

                if p.user:
                    teams[pkey].members.add(p.user)
                else:
                    teams[pkey].invites.create(email=p.invite_email, token=p.invite_token)

        teams = {}
        for p in o.user_perms.all():
            pkey = (p.can_create_events, p.can_change_permissions)
            if pkey not in teams:
                team = Team()
                team.can_change_organizer_settings = True
                team.can_create_events = p.can_create_events
                team.can_change_teams = p.can_change_permissions
                team.organizer = o
                team.name = '{} Team {}'.format(
                    str(o.name), len(teams) + 1
                )
                team.save()
                teams[pkey] = team

            if p.user:
                teams[pkey].members.add(p.user)
            else:
                teams[pkey].invites.create(email=p.invite_email, token=p.invite_token)


class Migration(migrations.Migration):

    dependencies = [
        ('pretixbase', '0051_auto_20170206_2027_squashed_0057_auto_20170501_2116'),
    ]

    operations = [
        migrations.CreateModel(
            name='Team',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=190, verbose_name='Team name')),
                ('all_events', models.BooleanField(default=False, verbose_name='All events (including newly created ones)')),
                ('can_create_events', models.BooleanField(default=False, verbose_name='Can create events')),
                ('can_change_teams', models.BooleanField(default=False, verbose_name='Can change permissions')),
                ('can_change_organizer_settings', models.BooleanField(default=False, verbose_name='Can change organizer settings')),
                ('can_change_event_settings', models.BooleanField(default=False, verbose_name='Can change event settings')),
                ('can_change_items', models.BooleanField(default=False, verbose_name='Can change product settings')),
                ('can_view_orders', models.BooleanField(default=False, verbose_name='Can view orders')),
                ('can_change_orders', models.BooleanField(default=False, verbose_name='Can change orders')),
                ('can_view_vouchers', models.BooleanField(default=False, verbose_name='Can view vouchers')),
                ('can_change_vouchers', models.BooleanField(default=False, verbose_name='Can change vouchers')),
                ('limit_events', models.ManyToManyField(to='pretixbase.Event', verbose_name='Limit to events')),
                ('members', models.ManyToManyField(related_name='teams', to=settings.AUTH_USER_MODEL, verbose_name='Team members')),
                ('organizer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='teams', to='pretixbase.Organizer')),
            ],
            options={
                'verbose_name_plural': 'Teams',
                'verbose_name': 'Team',
            },
        ),
        migrations.CreateModel(
            name='TeamInvite',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('email', models.EmailField(blank=True, max_length=254, null=True)),
                ('token', models.CharField(blank=True, default=pretix.base.models.organizer.generate_invite_token, max_length=64, null=True)),
                ('team', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='invites', to='pretixbase.Team')),
            ],
        ),
        migrations.RunPython(
            create_teams, migrations.RunPython.noop
        )
    ]
