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

from odoo import models, fields, api


class SOS_MME_List(models.Model):
    _name = 'sos_mme_list'
    _description = 'MASTER LIST OF MONITORING AND MEASURING EQUIPMENT'

    name = fields.Char(string="MME Name", required= True)
    mme_model = fields.Char(string="Make / Model")
    mme_supplied_by = fields.Char(string="Supplied By")
    mme_id = fields.Char(string="ID")
    mme_installed_on = fields.Date(string="Installed On")
    mme_history_card_no = fields.Char(
        readonly=False, required=True, string='History Card No', 
        default=lambda self: self._generate_id()
    )
    mme_used_in = fields.Char(string="Used in")
    mme_last_reviewed_on = fields.Date(string="Last Reviewed On")
    @api.model
    def create(self, vals):
        record = super(SOS_MME_List, self).create(vals)
        new_record = self.env['sos_mme_history_card'].create({
                                'name': record.id,
                                'mme_id':record.mme_id,
                                'mme_used_in':record.mme_used_in,
                                'mme_history_card_no':record.mme_history_card_no
                            })
        
        return record
    def _generate_id(self):
        model_name = 'sos_mme_list'
        form_prefix = 'HC-'
        field_name = 'mme_history_card_no'

        latest_record = self.env[model_name].sudo().search(
            [(field_name, 'like', f"{form_prefix}%")],
            order=f"{field_name} desc",
            limit=1
        )
        if latest_record and latest_record[field_name]:
            last_sequence = latest_record[field_name]
            try:
                last_number = int(last_sequence.replace(form_prefix, ''))
                new_number = last_number + 1
            except ValueError:
                new_number = 1
        else:
            new_number = 1

        return f"{form_prefix}{new_number:03d}"
