# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import django_countries.fields
import seminar.models
import django.utils.timezone
from django.conf import settings

CREATE_VIEWS="""
create view seminar_body_za_cislo as
  select
    sr.cislo_body_id || '-' || sr.resitel_id as id,
    sr.cislo_body_id as cislo_id,
    sr.resitel_id as resitel_id,
    sum(sr.body) as body
  from seminar_reseni as sr
  group by sr.cislo_body_id, sr.resitel_id
  order by body desc;

create view seminar_body_k_cislu as
  select
    akt_c.id || '-' || min_bzc.resitel_id as id,
    akt_c.id as cislo_id,
    min_bzc.resitel_id as resitel_id,
    max(akt_bzc.body) as body,
    sum(min_bzc.body) as body_celkem
  from ((seminar_cisla as akt_c
    inner join seminar_cisla as min_c on min_c.rocnik_id = akt_c.rocnik_id and akt_c.cislo >= min_c.cislo)
    inner join seminar_body_za_cislo as min_bzc on min_c.id = min_bzc.cislo_id)
    left outer join seminar_body_za_cislo as akt_bzc on akt_bzc.cislo_id = akt_c.id and akt_bzc.resitel_id = min_bzc.resitel_id 
  group by akt_c.id, min_bzc.resitel_id, akt_bzc.resitel_id
  order by body_celkem desc;
"""

DROP_VIEWS="""
drop view seminar_body_k_cislu;
drop view seminar_body_za_cislo;
"""

class Migration(migrations.Migration):

    dependencies = [("seminar", "0001_initial")]

    operations = [
        migrations.RunSQL(sql=CREATE_VIEWS, reverse_sql=DROP_VIEWS)
        ]