# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-08-18 22:28
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('base', '0100_bug_1390805_create_missing_tm_entries'),
    ]

    operations = [
        migrations.AddField(
            model_name='userprofile',
            name='custom_homepage',
            field=models.CharField(blank=True, max_length=10, null=True),
        ),
        migrations.RunSQL(
            # SQL migration that will group contributions and will assign locale with highest numbers of contributions
            # of a user as its custom_homepage.
            """
            WITH cte AS (
              SELECT au.id, au.email, bt.locale_id, count(bt.locale_id) as contributions_count, row_number()
              OVER(PARTITION BY au.id ORDER BY count(bt.locale_id) DESC) AS rn
              FROM auth_user au LEFT JOIN base_translation bt ON(bt.user_id=au.id)
              GROUP BY au.id, bt.locale_id
            )
            UPDATE base_userprofile bu SET custom_homepage = (
              SELECT code FROM base_locale WHERE id=cte.locale_id
            )
            FROM cte
            WHERE cte.rn=1 and cte.contributions_count > 0 and bu.user_id=cte.id;
            """,
            migrations.RunSQL.noop,
        )
    ]
