<commit_before># -*- coding: utf-8 -*-

from dateutil.rrule import rrule
from django.db import models
from django.utils.translation import ugettext as _
from python_dates.converters import int_to_weekday

from .constants import Frequency
from .fields import Recurrence
from .fields import RecurrenceField
from .managers import RecurrenceManager


class AbstractRecurrence(models.Model):
    """A model mixin for recurrence."""

    start_date = models.DateTimeField()
    end_date = models.DateTimeField(blank=True, null=True)
    recurrence = RecurrenceField(blank=True, null=True)
    objects = RecurrenceManager()

    class Meta:
        abstract = True

    def __init__(self, *args, **kwargs):

        if not hasattr(self, 'id') and not args:
            # New object creation that didn't from from database
            start_date = kwargs.get('start_date')
            end_date = kwargs.get('end_date')
            recurrence = kwargs.get('recurrence')

            # Ensure the start_date, end_date and recurrence are all in sync.
            # This will ensure if a start or end date is explicitly set that they
            # are set in the recurrence object as well.
            if recurrence:
                if start_date:
                    if isinstance(recurrence, dict):
                        recurrence['dtstart'] = start_date
                    elif hasattr(recurrence, 'dtstart'):
                        recurrence.dtstart = start_date

                if end_date:
                    if isinstance(recurrence, dict):
                        recurrence['until'] = end_date
                    elif hasattr(recurrence, 'until'):
                        recurrence.until = end_date

        super(AbstractRecurrence, self).__init__(*args, **kwargs)

    def save(self, *args, **kwargs):

        # self.end_date and recurrence.until should always be the same values.
        # They are denormalized for seachability purposes since recurrence is
        # just a json field and isn't efficient to query.

        if not self.end_date:
            self.end_date = self.get_end_date_from_recurrence()

        return super(AbstractRecurrence, self).save(*args, **kwargs)

    def __setattr__(self, name, value):
        """Check when setting attributes on a recurrence model to make sure
        and keep the following dates in sync:

        * start_date and recurrence.dtstart
        * end_date and recurrence.until

        """
        super(AbstractRecurrence, self).__setattr__(name, value)

        has_recurrence = hasattr(self, 'recurrence') and self.recurrence.is_recurring()

        if name == 'start_date' and has_recurrence:

            if self.recurrence.dtstart != self.start_date:
                self.recurrence.dtstart = self.start_date

        if name == 'end_date' and has_recurrence:

            if self.recurrence.until != self.end_date:
                self.recurrence.until = self.end_date

        if name == 'recurrence' and has_recurrence:

            self.start_date = self.recurrence.dtstart

            if self.recurrence.until:
                self.end_date = self.recurrence.until
            else:
                recurrence_end_date = self.get_end_date_from_recurrence()
                self.recurrence.until = recurrence_end_date
                self.end_date = recurrence_end_date

    def set_recurrence(self, freq, start_date, end_date=None, interval=1,
                       count=None, **kwargs):
        """
        :param freq: freq must be one of YEARLY (0), MONTHLY (1), WEEKLY (2),
            DAILY (3), HOURLY (4), MINUTELY (5), or SECONDLY (6)
        :param interval: The interval between each freq iteration. For example,<commit_msg>fix a start date bug<commit_after># -*- coding: utf-8 -*-

from dateutil.rrule import rrule
from django.db import models
from django.utils.translation import ugettext as _
from python_dates.converters import int_to_weekday

from .constants import Frequency
from .fields import Recurrence
from .fields import RecurrenceField
from .managers import RecurrenceManager


class AbstractRecurrence(models.Model):
    """A model mixin for recurrence."""

    start_date = models.DateTimeField()
    end_date = models.DateTimeField(blank=True, null=True)
    recurrence = RecurrenceField(blank=True, null=True)
    objects = RecurrenceManager()

    class Meta:
        abstract = True

    def __init__(self, *args, **kwargs):

        if not hasattr(self, 'id') and not args:
            # New object creation that didn't from from database
            start_date = kwargs.get('start_date')
            end_date = kwargs.get('end_date')
            recurrence = kwargs.get('recurrence')

            # Ensure the start_date, end_date and recurrence are all in sync.
            # This will ensure if a start or end date is explicitly set that they
            # are set in the recurrence object as well.
            if recurrence:
                if start_date:
                    if isinstance(recurrence, dict):
                        recurrence['dtstart'] = start_date
                    elif hasattr(recurrence, 'dtstart'):
                        recurrence.dtstart = start_date

                if end_date:
                    if isinstance(recurrence, dict):
                        recurrence['until'] = end_date
                    elif hasattr(recurrence, 'until'):
                        recurrence.until = end_date

        super(AbstractRecurrence, self).__init__(*args, **kwargs)

    def save(self, *args, **kwargs):

        # self.end_date and recurrence.until should always be the same values.
        # They are denormalized for seachability purposes since recurrence is
        # just a json field and isn't efficient to query.

        if not self.end_date:
            self.end_date = self.get_end_date_from_recurrence()

        return super(AbstractRecurrence, self).save(*args, **kwargs)

    def __setattr__(self, name, value):
        """Check when setting attributes on a recurrence model to make sure
        and keep the following dates in sync:

        * start_date and recurrence.dtstart
        * end_date and recurrence.until

        """
        super(AbstractRecurrence, self).__setattr__(name, value)

        has_recurrence = hasattr(self, 'recurrence') and self.recurrence.is_recurring()

        if name == 'start_date' and has_recurrence:

            if self.recurrence.dtstart != self.start_date:
                self.recurrence.dtstart = self.start_date

        if name == 'end_date' and has_recurrence:

            if self.recurrence.until != self.end_date:
                self.recurrence.until = self.end_date

        if name == 'recurrence' and has_recurrence:

            if self.recurrence.dtstart:
                self.start_date = self.recurrence.dtstart

            if self.recurrence.until:
                self.end_date = self.recurrence.until
            else:
                recurrence_end_date = self.get_end_date_from_recurrence()
                self.recurrence.until = recurrence_end_date
                self.end_date = recurrence_end_date

    def set_recurrence(self, freq, start_date, end_date=None, interval=1,
                       count=None, **kwargs):
        """
        :param freq: freq must be one of YEARLY (0), MONTHLY (1), WEEKLY (2),
            DAILY (3), HOURLY (4), MINUTELY (5), or SECONDLY (6)
        :param interval: The interval between each freq iteration. For example,
{'fraction_non_alphanumeric': 0.08229626655961461, 'fraction_numerical': 0.0024086712163789645, 'mean_word_length': 2.2368990905153745, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3191335', 'n_tokens_mistral': 2136, 'n_tokens_neox': 2044, 'n_words': 599}