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;
drop view seminar_body_za_cislo;

create view seminar_body_za_cislo as
  select
    seminar_reseni.cislo_body_id || '-' || seminar_reseni.resitel_id as id,
    seminar_reseni.cislo_body_id as cislo_id,
    seminar_reseni.resitel_id as resitel_id,
    seminar_cisla.cislo as cislo,
    seminar_cisla.rocnik_id as rocnik_id,
    seminar_rocniky.rocnik as rocnik,
    seminar_cisla.verejna_vysledkovka as verejna_vysledkovka,
    sum(seminar_reseni.body) as body
  from
    seminar_reseni
    inner join seminar_cisla on seminar_reseni.cislo_body_id = seminar_cisla.id
    inner join seminar_rocniky on seminar_cisla.rocnik_id = seminar_rocniky.id
  group by seminar_reseni.cislo_body_id, seminar_reseni.resitel_id, seminar_cisla.cislo,
    seminar_cisla.rocnik_id, seminar_rocniky.rocnik, seminar_cisla.verejna_vysledkovka
  order by body desc;

create view seminar_body_k_cislu_rocnik as
  select
    akt_body.id as id,
    akt_body.cislo_id as cislo_id,
    akt_body.resitel_id as resitel_id,
    akt_body.body as body,
    sum(min_body.body) as body_celkem
  from
    seminar_body_za_cislo as akt_body
    inner join seminar_body_za_cislo as min_body on
      (akt_body.resitel_id = min_body.resitel_id and
        (akt_body.rocnik = min_body.rocnik and akt_body.cislo >= min_body.cislo)
      )
  group by akt_body.id, akt_body.cislo_id, akt_body.resitel_id, akt_body.body
  order by body_celkem desc;

create view seminar_body_k_cislu_odjakziva as
  select
    akt_body.id as id,
    akt_body.cislo_id as cislo_id,
    akt_body.resitel_id as resitel_id,
    akt_body.body as body,
    sum(min_body.body) as body_celkem
  from
    seminar_body_za_cislo as akt_body
    inner join seminar_body_za_cislo as min_body on
      (akt_body.resitel_id = min_body.resitel_id and
        ((akt_body.rocnik = min_body.rocnik and akt_body.cislo >= min_body.cislo) or
         (akt_body.rocnik < min_body.rocnik)
        )
      )
  group by akt_body.id, akt_body.cislo_id, akt_body.resitel_id, akt_body.body
  order by body_celkem desc;

"""

class Migration(migrations.Migration):

    dependencies = [("seminar", "0027_export_flag_a_typ_akce")]

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