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

from odoo import models, fields, api
import re



class sos__aodr(models.Model):
    _name = 'sos_aodr'
    _description = 'Accept on Deviation Record '
    _rec_name = 'aodr_no'


    aodr_no = fields.Char(string="AODR No", readonly= True, required= True, default=lambda self: self._generate_id())
    aodr_date = fields.Date(string="AODR Date")
    source_of_deviation = fields.Many2one('selection_item', string='Source of Deviation')
    fg_name = fields.Many2one('sos_fg',string="FG Name")
    qp_no = fields.Char(related="fg_name.qp_no", string="QP No")
    batch_no = fields.Char(string="Batch No")
    doc_ref_no = fields.Many2one('sos_ncmr',string="NCMR Ref No")
    problem_cause = fields.Text(string="Description of Cause of Problem")
    identified_by = fields.Many2one('res.users', string='Authorised By')
    identified_sign_image = fields.Image(related="identified_by.signature_image",string='Authorised Signatory',readonly=True)
    reviewer_comments = fields.Text(string="Reviewer Comments")
    reviewed_by = fields.Many2one('res.users', string='Reviewd By')
    reviewer_sign_image = fields.Image(related="reviewed_by.signature_image",string='Reviewer Signatory',readonly=True)
    
    approval_name = fields.Many2one('res.users', string='Authorised By')
    approval_image = fields.Image(related="approval_name.signature_image",string='Authorised Signatory',readonly=True)

    def action_report_aodr_btn(self):
            try:
                action = self.env.ref("sos_inventory.action_report_aodr").report_action(self)
                return action
            except ValueError as e:
                print(f"Failed to find report action: {e}")

    def identified_by_sign_btn(self):
        sequence_util = self.env['sos_common_scripts']
        sequence_util.action_assign_signature(
        self, 
        'identified_by'
        )

    def reviewed_by_sign_btn(self):
        sequence_util = self.env['sos_common_scripts']
        sequence_util.action_assign_signature(
        self, 
        'reviewed_by'
        )

    def approved_by_sign_btn(self):
        sequence_util = self.env['sos_common_scripts']
        sequence_util.action_assign_signature(
        self, 
        'approval_name'
        )
    def _generate_id(self):
        sequence_util = self.env['sos_common_scripts']
        return sequence_util.generate_sequence('sos_aodr','AODR', 'aodr_no')

class SelectionItem(models.Model):
    _name = 'selection_item'
    _description = 'Selection Item'

    name = fields.Char(string='Name', required=True)