# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from urllib import urlencode
from urlparse import SplitResult
from urlparse import urlunsplit

from dateutil.relativedelta import relativedelta
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _

from core.models.reward import Reward

__all__ = ['Protocol']


@python_2_unicode_compatible
class Protocol(models.Model):

    class Meta:
        ordering = ['-created']

    created = models.DateTimeField(auto_now_add=True)
    start_date = models.DateTimeField(null=True, blank=True)
    staff_uid = models.BigIntegerField(null=True)
    staff_login = models.CharField(max_length=30, null=True)
    ticket_document = models.CharField(max_length=32, blank=True)
    ticket_kaznaops = models.CharField(max_length=32, blank=True)
    financial_report_file = models.BinaryField(null=True, blank=True)
    protocol_file = models.BinaryField(null=True, blank=True)

    def __str__(self):
        return _('Protocol of %s') % self.created.strftime('%F')

    def get_absolute_url(self):
        return urlunsplit(SplitResult(
            path=reverse('reward:list'),
            query=urlencode({'protocol': self.pk}),
            scheme=None, netloc=None, fragment=None))

    @property
    def rewards_processed(self):
        """Return number of processed(not PAYABLE) rewards."""
        return self.rewards.exclude(
            status__in=(Reward.ST_PAYABLE, Reward.ST_NEW)).count()

    @property
    def rewards_total(self):
        """Return total number of rewards."""
        return self.rewards.all().count()

    @property
    def processed(self):
        return self.rewards_processed == self.rewards_total

    @property
    def end_date(self):
        first_day_of_next_month = self.start_date + relativedelta(months=1)
        first_day_of_next_month = first_day_of_next_month.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        good_end = first_day_of_next_month - relativedelta(minutes=2)
        return good_end
