#-*- coding:utf-8 -*-

import codecs
import datetime

from django.contrib.auth.models import User
from django.core.management.base import BaseCommand

from dictionary.ajax_user_stats import get_lexical_stats, get_phraseology_stats, get_semantics_stats

class Command(BaseCommand):
    args = 'none'

    def handle(self, **options):
        get_payments()

def get_payments():
    now = datetime.datetime.now().strftime('%Y%m%d')
    payments_path = 'data/payments_%s.csv' % now
    payments_file = codecs.open(payments_path, 'wt', 'utf-8')
    users = User.objects.order_by('username')
    
    payments_file.write(u'Użytkownik\tFunkcja\tKwota zapłacona\tKwota za wykonaną pracę\tNadpłata\n')
    for user in users:
        print user
        function = user.groups.all()[0].name
        lex_work_stats = get_lexical_stats(user)
        phraseology_work_stats = get_phraseology_stats(user)
        semantics_work_stats = get_semantics_stats(user)
        total_earned_cash = round(lex_work_stats['earned_cash']+phraseology_work_stats['earned_cash']+semantics_work_stats['earned_cash'], 2)
        paid_cash = round(user.user_stats.paid_cash, 2)
        surcharge = round(user.user_stats.paid_cash-total_earned_cash, 2)
        if total_earned_cash > 0.0:
            payments_file.write(u'%s\t%s\t%.2f\t%.2f\t%.2f\n' % (user.username, function, 
                                                                 paid_cash, total_earned_cash, surcharge))                                                                
    payments_file.close()       
