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

from odoo import models, fields, _, api
from odoo.exceptions import UserError
from datetime import datetime, timedelta


class SuspendReasonWizard(models.TransientModel):
    _name = 'suspend.reason.wizard'

    _description = "Suspend Reason Wizard"

    def _default_entity(self):
        if self._context.get('active_model') == 'grant.benefit':
            return self._context.get('active_id')

    def _default_member(self):
        if self._context.get('active_model') == 'family.member':
            return self._context.get('active_id')

    def _default_state(self):
        return self._context.get('state')

    entity_id = fields.Many2one("grant.benefit", string="Entity", default=_default_entity)
    member_id = fields.Many2one("family.member", string="Member", default=_default_member)
    suspend_reason = fields.Many2one('suspend.reason', string='Suspend Reason',
                                     domain=lambda self: self._get_suspend_reason_domain(), required=True)
    suspend_description = fields.Text(string='Suspend Description', required=True)
    suspend_attachment = fields.Binary(string='Suspend Attachment', attachment=True)
    final_suspend_date = fields.Date(string="Final Suspend Date", default=fields.Date.context_today)
    resume_date = fields.Date(string="Resume Date", default=fields.Date.today)

    @api.onchange('suspend_reason')
    def _onchange_compute_final_suspend_date(self):
        if self.suspend_reason and self.suspend_reason.suspend_type == 'temporarily_suspend':
            days = self.suspend_reason.days_before_final_suspend or 0
            self.final_suspend_date = datetime.today().date() + timedelta(days=days)
        else:
            self.final_suspend_date = fields.Date.context_today(self)

    def _get_suspend_reason_domain(self):
        domain = []
        if self._context.get('resume_family'):
            domain.append(('is_resume_reason', '=', True))
        else:
            domain.append(('is_stop_reason', '=', True))

        if self._context.get('active_model') == 'family.member':
            domain.append(('entity_type', '=', 'member'))
        elif self._context.get('active_model') == 'grant.benefit':
            domain.append(('entity_type', '=', 'family'))

        return domain

    def _create_attachment_record_from_binary(self):
        self.ensure_one()

        linked_record = self.entity_id or self.member_id
        if not linked_record:
            UserError(
                _('There is no record to link the binary to it!')
            )
        binary_file = self.suspend_attachment
        attachment_vals = {
            'name': 'suspend_attachment_%s' % (linked_record.id or 'tmp'),
            'datas': binary_file,
            'res_model': 'grant.benefit',
            'res_id': linked_record.id,
            'type': 'binary',
        }

        return self.env['ir.attachment'].create(attachment_vals)

    def action_submit(self):
        for rec in self:
            benefit = rec.entity_id
            if not benefit:
                raise UserError(_("No family record found."))

            if self._context.get('resume_family'):
                action_type = ('resume_from_temporary'
                               if benefit.state == 'temporary_suspended'
                               else 'resume_from_final')
                benefit.member_ids.write({
                    'action_type': action_type,
                })
                vals = {
                    'state': 'waiting_approve',
                    'action_type': action_type,
                    'resume_reason_id': rec.suspend_reason.id,
                    'resume_date': rec.resume_date,
                    'resume_notes': rec.suspend_description,
                }
            else:
                if rec.suspend_reason.check_all_members_non_benefit:
                    if benefit.benefit_member_count > 0:
                        raise UserError(
                            _("Operation not allowed: The family has %s benefit member(s). All members must be non-benefit to proceed.") % benefit.benefit_member_count)
                benefit.member_ids.write({
                    'is_excluded_suspension': False,
                    'is_member_workflow': False,
                    'final_suspend_date': rec.final_suspend_date,
                    'action_type': 'suspended',
                })
                if rec.suspend_attachment:
                    attachment = rec._create_attachment_record_from_binary()
                    benefit.suspend_attachment = [(4, attachment.id)]

                vals = {
                    'state': 'waiting_approve',
                    'action_type': 'suspended',
                    'suspend_reason': rec.suspend_reason.id,
                    'suspend_description': rec.suspend_description,
                    'suspend_type': rec.suspend_reason.suspend_type,
                    'suspend_method': 'manual',
                    'final_suspend_date': rec.final_suspend_date,
                    'is_excluded_suspension': False,
                }
            benefit.write(vals)

    def action_member_submit(self):
        for rec in self:
            member = rec.member_id
            if not member:
                raise UserError(_("No member record found."))

            if self._context.get('resume_family'):
                action_type = ('resume_from_temporary'
                               if member.state == 'temporary_suspended'
                               else 'resume_from_final')

                vals = {
                    'state_a': 'waiting_approve',
                    'action_type': action_type,
                    'resume_reason_id': rec.suspend_reason.id,
                    'resume_date': rec.resume_date,
                    'resume_notes': rec.suspend_description,
                }
            else:
                vals = {
                    'state_a': 'waiting_approve',
                    'action_type': 'suspended',
                    'suspend_reason': rec.suspend_reason.id,
                    'suspend_description': rec.suspend_description,
                    'suspend_type': rec.suspend_reason.suspend_type,
                    'suspend_method': 'manual',
                    'final_suspend_date': rec.final_suspend_date,
                    'is_member_workflow': True,
                    'is_excluded_suspension': False,
                }

                if rec.suspend_attachment:
                    attachment = rec._create_attachment_record_from_binary()
                    member.suspend_attachment = [(4, attachment.id)]
            member.write(vals)
