# -*- coding: utf-8 -*-
# Generated by Django 1.11b1 on 2017-03-02 19:43
from __future__ import unicode_literals

from django.db import migrations


def create_trigger(apps, schema_editor):
    if schema_editor.connection.vendor == "postgresql":
        schema_editor.execute(
            """
            CREATE OR REPLACE FUNCTION update_full_account_codes()
                RETURNS TRIGGER AS
            $$
            BEGIN
                UPDATE
                    hordak_account AS a
                SET
                    full_code = (
                        SELECT string_agg(code, '' order by lft)
                        FROM hordak_account AS a2
                        WHERE a2.lft <= a.lft AND a2.rght >= a.rght AND a.tree_id = a2.tree_id
                    );
                RETURN NULL;
            END;
            $$
            LANGUAGE plpgsql;
        """
        )
        schema_editor.execute(
            """
            CREATE TRIGGER update_full_account_codes_trigger
            AFTER INSERT OR UPDATE OR DELETE ON hordak_account
            WHEN (pg_trigger_depth() = 0)
            EXECUTE PROCEDURE update_full_account_codes();
        """
        )
    elif schema_editor.connection.vendor == "mysql":
        pass  # we don't care about MySQL here since support is added in xxxx
    else:
        raise NotImplementedError(
            "Don't know how to create trigger for %s" % schema_editor.connection.vendor
        )


def drop_trigger(apps, schema_editor):
    if schema_editor.connection.vendor == "postgresql":
        schema_editor.execute(
            "DROP TRIGGER IF EXISTS update_full_account_codes_trigger ON hordak_account"
        )
        schema_editor.execute("DROP FUNCTION update_full_account_codes()")
    elif schema_editor.connection.vendor == "mysql":
        pass  # we don't care about MySQL here since support is added in 0027
    else:
        raise NotImplementedError(
            "Don't know how to drop trigger for %s" % schema_editor.connection.vendor
        )


class Migration(migrations.Migration):
    dependencies = [("hordak", "0012_account_full_code")]

    operations = [
        migrations.RunPython(create_trigger, reverse_code=drop_trigger),
    ]
