# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-11-18 00:16
from __future__ import unicode_literals

from django.db import migrations

def set_tx_type(apps, schema_editor):
    """Computes the type of a transaction based on the checkin type"""
    Contest_Checkin = apps.get_model('beers', 'Contest_Checkin')
    for checkin in Contest_Checkin.objects.all():
        if checkin.contest_beer is not None:
            # Check if this is a challenge beer
            if checkin.contest_beer.challenger is not None:
                if checkin.contest_beer.challenger.id == checkin.contest_player.id:
                    checkin.tx_type = 'CS'
                else:
                    checkin.tx_type = 'CO'
            else:
                checkin.tx_type = 'BE'
        elif checkin.contest_brewery is not None:
            checkin.tx_type = 'BR'
        checkin.save()

def create_challenge_point_txs(apps, schema_editor):
    """
    Searches through checkins and finds the set of challenges that a challenger
    lost
    """
    Contest_Checkin = apps.get_model('beers', 'Contest_Checkin')
    checkins = Contest_Checkin.objects.filter(tx_type='CO').order_by('contest_beer', 
                                                                     'checkin_time')
    current_beer = None
    loss = 0
    for checkin in checkins:
        if current_beer != checkin.contest_beer:
            loss = 0
            current_beer = checkin.contest_beer
        if loss + current_beer.challenge_point_loss <= current_beer.max_point_loss:
            loss = loss + current_beer.challenge_point_loss
            co_checkin = Contest_Checkin(
                tx_type='CL',
                contest_player=current_beer.challenger,
                contest_beer=current_beer,
                checkin_points=-current_beer.challenge_point_loss,
                untappd_checkin=checkin.untappd_checkin,
                checkin_time=checkin.checkin_time)
            co_checkin.save()

def delete_challenge_point_txs(apps, schema_editor):
    """
    Deletes all the challenge point losses
    """
    Contest_Checkin = apps.get_model('beers', 'Contest_Checkin')
    Contest_Checkin.objects.filter(tx_type='CL').delete()

class Migration(migrations.Migration):

    dependencies = [
        ('beers', '0023_auto_20171117_2005'),
    ]

    operations = [
        migrations.RunPython(set_tx_type),
        migrations.RunPython(create_challenge_point_txs, 
                             delete_challenge_point_txs)

    ]
