# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2017-01-26 22:08
from __future__ import unicode_literals

from django.db import migrations

sql = """
CREATE FUNCTION init_customers(customers_num integer, emails_num integer, phones_num integer) RETURNS VOID AS $$

random_name = "(ARRAY['Иван','Илья','Павел','Боромир','Златоуст'])[ceil(random() * 5)]"
random_surname = "(ARRAY['Сидоров','Бонд','Смит','Колобков','Иванов'])[ceil(random() * 5)]"
customers_query = "INSERT INTO web_site_customer (first_name, last_name) SELECT %s, %s FROM generate_series(1, %s) as i;" % (random_name, random_surname, customers_num)
plpy.execute(customers_query)

response = plpy.execute("SELECT MAX(id) AS max_id, MIN(id) AS min_id FROM web_site_customer;")
customers_min_id = response[0]['min_id']
customers_max_id = response[0]['max_id']

random_phone = "'+' || ceil(random() * 100000000000)"
random_owner = "trunc(random() * ({end} - {start}) + {start})".format(start=customers_min_id, end=customers_max_id)
phone_query = "INSERT INTO web_site_phone (number, customer_id) SELECT %s, %s FROM generate_series(1, %s) as i;" % (random_phone, random_owner, phones_num)
plpy.execute(phone_query)

domain = "(ARRAY['gmail','yandex','mail','yahoo'])[ceil(random() * 4)]"
domain_zone = "(ARRAY['ru','com','uk'])[ceil(random() * 3)]"
email_name = "left(md5(i::text), 10)"
random_email = "%s || '@' || %s || '.' || %s" % (email_name, domain, domain_zone)
email_query = "INSERT INTO web_site_email (address, customer_id) SELECT %s, %s FROM generate_series(1, %s) as i;" % (random_email, random_owner, emails_num)
plpy.execute(email_query)

$$ LANGUAGE plpythonu;

SELECT init_customers(2100000, 2000000, 2000000);
ANALYZE web_site_customer;
ANALYZE web_site_email;
ANALYZE web_site_phone;
"""


class Migration(migrations.Migration):
    dependencies = [
        ('web_site', '0001_initial'),
    ]

    operations = [
        migrations.RunSQL(sql)
    ]
