# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-05-16 20:59
from __future__ import unicode_literals

from django.db import migrations

def spoj_k_organizatorum_osoby(apps, scema_editor):	
	Organizator = apps.get_model('seminar', 'Organizator')
	Resitel = apps.get_model('seminar', 'Resitel')
	Osoba = apps.get_model('seminar', 'Osoba')
	for org in Organizator.objects.all():
		
		# Spárování organizátora s osobou
		user = org.user
		resitele = Resitel.objects.filter(user=user)
		if resitele.count() != 0:
			osoba = resitele.first().osoba
		else:
			osoba = Osoba(user=user)

			# Přesun informací z usera do osoby
			# pro řešitele již v minule migraci
			osoba.jmeno = user.first_name
			osoba.prijmeni = user.last_name 
			osoba.email = user.email
			user.jmeno = "Použij osobu!"
			user.prijmeni = "Použij osobu!"
			user.email = "Použij osobu!"
			user.save()

		# Přesun informací z organizátora do jeho osoby
		osoba.prezdivka = org.prezdivka if org.prezdivka is not None else ''
		osoba.foto = org.foto
		
		# Všechno uložit
		osoba.save()
		org.osoba = osoba
		org.save()
		
def fix_problem(apps, schema_editor):
	Problem = apps.get_model('seminar', 'Problem')
	Organizator = apps.get_model('seminar', 'Organizator')
	for pr in Problem.objects.all():
		if pr.autor_old is not None:
			pr.autor = Organizator.objects.filter(osoba__user=pr.autor_old).first()
		else:
			pr.autor = None
		if pr.opravovatel is not None:
			pr.opravovatele.add(Organizator.objects.filter(osoba__user=pr.opravovatel).first())
		pr.save()

def fix_pohadka(apps, schema_editor):
	Pohadka = apps.get_model('seminar', 'Pohadka')
	Organizator = apps.get_model('seminar', 'Organizator')
	for poh in Pohadka.objects.all():
		if poh.autor_old is not None:
			poh.autor = Organizator.objects.filter(osoba__user=poh.autor_old).first()
		else:
			poh.autor = None
		poh.save()

def fix_novinka(apps, schema_editor):
	Novinky = apps.get_model('seminar', 'Novinky')
	Organizator = apps.get_model('seminar', 'Organizator')
	for nov in Novinky.objects.all():
		nov.autor = Organizator.objects.filter(osoba__user=nov.autor_old).first()
		nov.save()
	
	

class Migration(migrations.Migration):

	dependencies = [
		('seminar', '0051_resitel_to_osoba'),
	]

	operations = [
		migrations.RunPython(spoj_k_organizatorum_osoby),
		migrations.RunPython(fix_problem),
		migrations.RunPython(fix_pohadka),
		migrations.RunPython(fix_novinka),
	]