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

from odoo import models, fields, api
from datetime import date


class SOS_MME_HC(models.Model):
    _name = 'sos_mme_history_card'
    _description = 'MME History Card'
    _order = 'id asc' 
    name = fields.Many2one('sos_mme_list',string="MME Name", required= True)
    mme_id = fields.Char(related="name.mme_id",string="MME ID")
    mme_history_card_no = fields.Char(related="name.mme_history_card_no",string="History Card No")
    mme_range = fields.Char(string="MME Range")
    calibration_frequency = fields.Char(string="Calibration Frequency")
    mme_opreating_range = fields.Char(string="MME Operating Range")
    calibrated_at = fields.Selection([ ('In-House', 'In-House'),('Out-Sourced', 'Out-Sourced')],default='In-House',string="Calibrated At")
    margin_tolerance = fields.Char(string="Margin of Tolerance")
    iso_std = fields.Char(string="ISO Standard Reference")
    mme_used_in = fields.Char(related="name.mme_used_in",string="Used in")
    inhouse_mme_name=fields.Char(string="Master MME Name and ID No")
    line_ids = fields.One2many('sos_mme_history_card_line', 'ref_id', string="History", ondelete='cascade')
    

class SOS_MME_HC_Line(models.Model):
    _name = 'sos_mme_history_card_line'
    _description = 'MME History Card Lines'

    ref_id = fields.Many2one('sos_mme_history_card', string="History", ondelete="cascade")
    name = fields.Many2one('sos_mme_list',related="ref_id.name", store=True)
    mme_id = fields.Char(related="ref_id.mme_id",string="MME ID")
    mme_history_card_no = fields.Char(related="ref_id.mme_history_card_no",string="History Card No")
    mme_used_in = fields.Char(related="ref_id.mme_used_in",string="MME Location")
    company_name= fields.Char(string="Calibration Company Name")
    calibration_due_date = fields.Date(string="Calibration Due Date")
    actual_calibrated_date = fields.Date(string="Actual Calibrated Date")
    certificate_no = fields.Char(string="Calibration Certificate No")
    calibration_results = fields.Selection([ ('PASS', 'PASS'),('FAIL', 'FAIL')],string="Calibrated Results")
    next_calibration_on = fields.Date(string="Next Calibration Due")
    is_latest = fields.Boolean(string='Is Latest', compute='_compute_is_latest', store=True)
    remaining_days = fields.Integer(string="Remaining Days for Calibration", compute="_compute_remaining_days", store=True)
    next_turn_around_time = fields.Char(string="Calibration Turn-Around Time", compute="_compute_turn_around_time")
    certificate = fields.Binary("Certificate")
    certificate_filename=fields.Char(string="certificate Name")
    def action_view_certificate(self):
        self.ensure_one()
        if not self.certificate:
            raise UserError("No Certificate available for this record.")

        return {
            'type': 'ir.actions.act_url',
            'url': '/web/content?model=%s&id=%d&field=certificate&filename_field=certificate_filename&download=false' % (
                self._name, self.id),
            'target': 'new',
        }
    @api.depends('calibration_due_date', 'actual_calibrated_date')
    def _compute_turn_around_time(self):
        for record in self:
            if record.calibration_due_date and record.actual_calibrated_date:
                # Calculate the difference in days
                delta = (record.actual_calibrated_date - record.calibration_due_date).days
                record.next_turn_around_time = f"{delta} Days"
            else:
                # If either date is missing, leave the field empty
                record.next_turn_around_time = "0 Days"

    def action_mme_list(self):
        self.env.cr.execute("""
           SELECT DISTINCT ON (name) id, name
FROM sos_mme_history_card_line
ORDER BY name, id DESC;
        """)
        unique_ids = [row[0] for row in self.env.cr.fetchall()]

        records = self.browse(unique_ids)
        if not records:
            raise UserError("No records found to print.")

        return self.env.ref('sos_inventory.mme_history_card_report').with_context(landscape=True).report_action(records)
     
    @api.depends('name')
    def _compute_is_latest(self):
        for record in self:
            if record.name:
                # Get all records with the same name
                all_records = self.search([('name', '=', record.name.name)])
                
                # Find the latest record (highest ID)
                latest_record = all_records.sorted(lambda r: r.id, reverse=True)[0]
                
                # Mark the latest record as True
                for rec in all_records:
                    rec.is_latest = rec.id == latest_record.id

    @api.depends('next_calibration_on')
    def _compute_remaining_days(self):
        for record in self:
            if record.next_calibration_on:
                today = date.today()
                remaining_days = (record.next_calibration_on - today).days
                record.remaining_days = remaining_days
            else:
                record.remaining_days = 0