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="""

drop view seminar_body_k_cislu_rocnik;
create view seminar_body_k_cislu_rocnik as
  select
    seminar_cisla.id || '-' || min_body.resitel_id as id,
    seminar_cisla.id as cislo_id,
    min_body.resitel_id as resitel_id,
    sum(min_body.body) as body
  from
    seminar_cisla
    inner join seminar_body_za_cislo as min_body on
      (min_body.rocnik_id = seminar_cisla.rocnik_id and seminar_cisla.cislo >= min_body.cislo)
  group by seminar_cisla.id, min_body.resitel_id
  order by body desc;

drop view seminar_body_k_cislu_odjakziva;
create view seminar_body_k_cislu_odjakziva as
  select
    seminar_cisla.id || '-' || min_body.resitel_id as id,
    seminar_cisla.id as cislo_id,
    min_body.resitel_id as resitel_id,
    sum(min_body.body) as body
  from
    seminar_cisla
    inner join seminar_rocniky on
      (seminar_cisla.rocnik_id = seminar_rocniky.id)
    inner join seminar_body_za_cislo as min_body on
      (min_body.rocnik_id = seminar_cisla.rocnik_id and seminar_cisla.cislo >= min_body.cislo) or
      (min_body.rocnik < seminar_rocniky.rocnik)
  group by seminar_cisla.id, min_body.resitel_id
  order by body desc;
"""

class Migration(migrations.Migration):

    dependencies = [("seminar", "0028_add_body_celkem_views")]

    operations = [
        migrations.RunSQL(sql=CREATE_VIEWS)
        ]