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

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


class ScopDecesWizard(models.TransientModel):
    _name = 'scop.deces.wizard'
    _description = "Décés"

    # Default functions
    @api.model
    def _default_partner_id(self):
        return self.env.context.get('active_id')

    @api.model
    def _default_last_period_id(self):
        return self.env['scop.period'].search(
            [('partner_id', '=', self.env.context.get('active_id')),
             ('end', '=', False)],
            limit=1).id

    # Fields common
    partner_id = fields.Integer('Partner', default=_default_partner_id)

    # Fields previous period
    last_period_id = fields.Integer(default=_default_last_period_id)
    end = fields.Date(
        'Fin de validité', required=True, default=fields.Date.today())
    dissolution_reason_id = fields.Many2one(
        'res.partner.dissolution.reason',
        string="Motif Décés",
        on_delete='restrict',
        required=True)
    comments = fields.Text('Commentaires')

    @api.multi
    def deces_action(self):
        # Close previous period
        for period in self:
            last_period = self.env['scop.period'].browse(
                period.last_period_id)
            if last_period:
                if period.end >= last_period.start:
                    last_period.write({
                        'end': period.end,
                        'end_reason': 'deces',
                        'dissolution_reason_id':
                            period.dissolution_reason_id.id,
                        'comments': period.comments,
                    })
                else:
                    raise ValidationError(
                        "La date de fin doit être postèrieure à la date de "
                        + "début de la dernière période: "
                        + str(last_period.start))

                # Update partner
                partner = self.env['res.partner'].browse(period.partner_id)
                partner.write({
                    'dissolution_date': period.end,
                    'dissolution_reason_id': period.dissolution_reason_id.id
                })

                #.........................................
                # HS 08/04/2020
                # On procède à la radiation à la même date
                #..........................................
                # Lecture du motif de radiation type décès
                motif = self.env['scop.membership.reason.end'].search([
                ('name', '=', 'Mort économique')], limit=1)

                # Mise à jour des périodes d'adhésions
                if motif:
                    adh_period = self.env['scop.membership.period'].search(
                    [('partner_id', '=', period.partner_id), ('end', '=', False)])
                    for adh in adh_period:
                        adh.write({
                        'end': period.end,
                        'end_reason_id': motif.id
                        })

            else:
                raise ValidationError(
                    "Il n'existe pas de période à fermer.")