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

from odoo import models, fields, api, _
from datetime import datetime, timedelta
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT


class VisitLocationRefusalReasonWizard(models.TransientModel):
    _name = "visit.location.refusal.reason.wizard"
    _description = "Reason for Visit Refusal"

    def _default_visit_location_id(self):
        return self._context.get('active_id')

    def _get_target_state(self):
        return self._context.get('target_state', 'cancel')

    visit_location_id = fields.Many2one("visit.location", string="Visit", default=_default_visit_location_id)
    suspend_reason_id = fields.Many2one("suspend.reason", string="Refusal Reason", required=True,
                                        domain=[('is_family_return_reason', '=', True)])
    refusal_notes = fields.Text(string='Notes', required=True)
    target_state = fields.Char(string='Target State', default=_get_target_state)

    def action_confirm_return(self):
        for rec in self:
            if rec.visit_location_id:
                target_state = rec.target_state
                state_label = dict(rec.visit_location_id.fields_get(['state'])['state']['selection']).get(target_state,
                                                                                                  target_state)

                subject = _('Visit')
                body = _(
                    "The visit record <b>%s</b> state has been changed to <b>%s</b>.<br/>"
                    "Refusal Reason: <b>%s</b><br/>"
                    "Notes: <b>%s</b>") % (
                       rec.visit_location_id.name, state_label, rec.suspend_reason_id.name or '', rec.refusal_notes or '')

                rec.visit_location_id.message_post(
                    body=body,
                    subject=subject,
                    message_type='notification'
                )

                rec.visit_location_id.sudo().write({"state": target_state, "reason": rec.refusal_notes})

                return {'type': 'ir.actions.act_window_close'}
