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

class HelpdeskTeamInherit(models.Model):
    _inherit = 'helpdesk.team'

    helpdesk_ticket_type_id = fields.Many2one('helpdesk.ticket.type','Tipo de ticket',copy=False)
    short_name = fields.Char('Nombre corto',copy=False)
    sequence_id = fields.Many2one('ir.sequence',string="Sequencia",copy=False)


    @api.onchange(short_name)
    def convert_short_name_upper(self):
        if self.short_name:
            name = self.short_name
            self.short_name = name.upper()


    def write(self,vals):
        res = super(HelpdeskTeamInherit, self).write(vals)
        if 'name' in vals:
            self.create_helpdesk_ticket_type()
        if 'short_name' in vals:
            self.create_sequence()
        return res

 
    def copy(self, default=None):
        if default is None:
            default = {}
        if 'name' not in default:
            default['name'] = _("%s (copia)") % self.name
            default['short_name'] = _("%s (copia)") % self.short_name
        return super(HelpdeskTeamInherit, self).copy(default=default)



    @api.model
    def create(self,vals):
        res = super(HelpdeskTeamInherit, self).create(vals)
        res.create_helpdesk_ticket_type()
        res.create_sequence()
        return res


    def create_helpdesk_ticket_type(self):
        if not self.helpdesk_ticket_type_id:
            ticket_type = self.env['helpdesk.ticket.type'].sudo().create({'name':self.name})
            if ticket_type:
                self.helpdesk_ticket_type_id = ticket_type.id
        else:
            self.helpdesk_ticket_type_id.name = self.name


    def create_sequence(self):
        if not self.sequence_id:
            sequence = self.env['ir.sequence'].sudo().create({
                'name': "Helpdesk Ticket sequence "+self.name,
                'code': "helpdesk.ticket."+str(self.id),
                'prefix': self.short_name+"/",
                'padding': 4
            })
            self.sequence_id = sequence.id
        else:
            self.sequence_id.prefix = self.short_name