# -*- coding: utf-8 -*-
import datetime
import logging
from collections import defaultdict
from south.db import db
from south.v2 import DataMigration
from django.db import models

stat_attrs = 'channel_count_err length_err mismatch_data_err no_link_err waiting downloaded to_download'.split()

def get_stats(orders):
    stats = defaultdict(int)
    for o in orders:
        for attr in stat_attrs:
            if o.get(attr):
                stats[attr] += 1
        if o['waiting'] == False and o['no_link_err'] == False:
            stats['downloadable'] += 1
    stats['ordered'] = len(orders)
    return stats
        
        
class Migration(DataMigration):
    def forwards(self, orm):
        for obj in orm['orders.Region'].objects.filter(uik__orders__isnull = False).distinct():
            logging.info(u'Обновляется састистика region:%s', obj.pk)
            orders = orm['orders.Order'].objects.filter(uik__region_id = obj.pk).values(*stat_attrs)
            orm['orders.Region'].objects.filter(id = obj.pk).update(**get_stats(orders))
        for obj in orm['orders.UIK'].objects.filter(orders__isnull = False).distinct():
            logging.info(u'Обновляется састистика uik:%s', obj.pk)
            orders = orm['orders.Order'].objects.filter(uik_id = obj.pk).values(*stat_attrs)
            orm['orders.UIK'].objects.filter(id = obj.pk).update(**get_stats(orders))
                

    def backwards(self, orm):
        "Write your backwards methods here."

    models = {
        u'orders.order': {
            'Meta': {'object_name': 'Order'},
            'archive_data': ('picklefield.fields.PickledObjectField', [], {'null': 'True'}),
            'archive_urls': ('picklefield.fields.PickledObjectField', [], {'null': 'True'}),
            'channel_count_err': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
            'downloaded': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'length_err': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'mismatch_data_err': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'no_link_err': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'orderid': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20', 'db_index': 'True'}),
            'orderstatus': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True'}),
            'tend': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
            'to_download': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'tstart': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
            'uik': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'orders'", 'to': u"orm['orders.UIK']"}),
            'unavailable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'waiting': ('django.db.models.fields.BooleanField', [], {'default': 'True'})
        },
        u'orders.region': {
            'Meta': {'ordering': "['name']", 'object_name': 'Region'},
            'channel_count_err': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '10'}),
            'downloadable': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'downloaded': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'length_err': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'mismatch_data_err': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'name': ('django.db.models.fields.TextField', [], {}),
            'no_link_err': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'ordered': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'to_download': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'waiting': ('django.db.models.fields.IntegerField', [], {'default': '0'})
        },
        u'orders.uik': {
            'Meta': {'object_name': 'UIK'},
            'channel_count_err': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '10'}),
            'downloadable': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'downloaded': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'length_err': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'mismatch_data_err': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'name': ('django.db.models.fields.TextField', [], {}),
            'no_link_err': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'num': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
            'ordered': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'region': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['orders.Region']"}),
            'tmax': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
            'tmin': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
            'to_download': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'waiting': ('django.db.models.fields.IntegerField', [], {'default': '0'})
        }
    }

    complete_apps = ['orders']
    symmetrical = True
