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

""" Weekly massive event creation module """

import logging
from datetime import timedelta
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError
_LOGGER = logging.getLogger(__name__)

class CoworkingEventWeekly(models.TransientModel):
    """ Weekly massive event creation """
    _name = 'coworking.event.weekly'
    _description = 'Weekly massive event creation'

    title = fields.Char(required=True)
    manager_id = fields.Many2one('coworking.res_partner', string='Manager',
                                 required=True)
    date_start_recurence = fields.Datetime('Date start', required=True)
    date_stop_recurence = fields.Datetime('Date stop', required=True)
    duration = fields.Float(required=True)

    @api.constrains('date_start_recurence', 'date_stop_recurence')
    def _check_dates(self):
        """ Check date coherence """
        for weekly in self:
            if weekly.date_start_recurence > weekly.date_stop_recurence:
                raise ValidationError(_('Please check you dates.'))

    @api.multi
    def weekly_create(self):
        """ Create multiple events repeated weekly, according to dates """
        self.ensure_one()
        # 5 - Rediriger vers la liste des événements (en automatique)
        # _LOGGER.warning()
        date_start_py = fields.Datetime.from_string(self.date_start_recurence)
        duration_delta = timedelta(hours=self.duration)
        date_stop_py = fields.Datetime.from_string(self.date_stop_recurence)
        delta = date_stop_py - date_start_py

        wdelta = timedelta(days=7)

        for week_number in xrange(delta.days / 7 + 1):
            if week_number == 0:
                date_start = self.date_start_recurence
                date_stop = fields.Datetime.to_string(date_start_py + duration_delta)
            else:
                date_start = fields.Datetime.from_string(self.date_start_recurence) +\
                             wdelta * week_number
                date_stop = fields.Datetime.to_string(date_start + duration_delta)
                date_start = fields.Datetime.to_string(date_start)
            self.env['coworking.event'].create({
                'title': self.title,
                'date_start': date_start,
                'date_end': date_stop,
                'manager_id': self.manager_id.id
                })
        event_action = self.env.ref('coworking_event.event_action')
        return {
            'type': event_action.type,
            'name': event_action.name,
            'res_model': event_action.res_model,
            'target': 'main',
            'view_mode': event_action.view_mode
            }