# © 2019 Le Filament (<http://www.le-filament.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from odoo import models, fields, api
from odoo.exceptions import UserError, ValidationError


class ScopHrTimesheet(models.Model):
    _inherit = "account.analytic.line"

    def _default_ur(self):
        return self.env['res.company']._ur_default_get()

    name = fields.Char(required=False)
    cgscop_timesheet_code_id = fields.Many2one(
        related='project_id.cgscop_timesheet_code_id',
        string='Code Activité National',
        store=True)
    ur_financial_system_id = fields.Many2one(
        comodel_name='ur.financial.system',
        string='Dispositif Financier')
    ur_id = fields.Many2one(
        'union.regionale',
        string='Union Régionale',
        index=True,
        on_delete='restrict',
        default=_default_ur)
    sheet_id = fields.Many2one(
        comodel_name='cgscop.timesheet.sheet',
        string="Feuille de temps",
        readonly=True,
        copy=False)
    state = fields.Selection([
        ('to_report', 'A rapporter'),
        ('draft', 'Brouillon'),
        ('submit', 'Soumis'),
        ('valid', 'Validé')],
        compute='_compute_state',
        string='Statut',
        copy=False,
        index=True,
        readonly=True,
        store=True,)

    # ------------------------------------------------------
    # Compute Functions
    # ------------------------------------------------------
    @api.depends('sheet_id', 'sheet_id.state')
    def _compute_state(self):
        for timesheet in self:
            if not timesheet.sheet_id:
                timesheet.state = "to_report"
            else:
                timesheet.state = timesheet.sheet_id.state

    # ------------------------------------------------------
    # OnChange Functions
    # ------------------------------------------------------
    @api.onchange('project_id')
    def onchange_project_id(self):
        self.partner_id = self.project_id.partner_id

    # ------------------------------------------------------
    # Override ORM
    # ------------------------------------------------------
    @api.multi
    def unlink(self):
        for timesheet in self:
            if timesheet.state in ['submit', 'valid']:
                raise UserError('Vous ne pouvez pas supprimer une '
                                'ligne de temps soumise ou validée')
        super(ScopHrTimesheet, self).unlink()

    # ------------------------------------------------------
    # Actions
    # ------------------------------------------------------
    @api.multi
    def action_submit_timesheet_lines(self):
        """
            Crée une feuille de temps avec les lignes sélectionnées
        """
        if any(time.state != 'to_report' or time.sheet_id for time in self):
            raise UserError(
                "Vous ne pouvez pas insérer 2 fois la même ligne !")
        if len(self.mapped('employee_id')) != 1:
            raise UserError(
                "Il ne peut y avoir plusieurs employés dans une "
                "même feuille de temps.")

        return {
            'name': 'New Expense Report',
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'res_model': 'cgscop.timesheet.sheet',
            'target': 'current',
            'context': {
                'default_timesheet_line_ids': self.ids,
                'default_employee_id': self[0].employee_id.id,
                'default_name': self[0].name if len(self) == 1 else ''
            }
        }