import base64
from odoo import models, fields, api
from openpyxl import load_workbook
from io import BytesIO

class MON_BulkUploadWizard(models.TransientModel):
    _name = 'mon_bulk_upload_wizard'
    _description = 'MON Wizard for Bulk Uploading Materials'

    upload_file = fields.Binary("Upload File", required=True)
    mon_id = fields.Many2one('sos_mon', string="MON Record")

    def upload_action(self):
        file_content = base64.b64decode(self.upload_file)
        file_stream = BytesIO(file_content)
        workbook = load_workbook(file_stream)
        worksheet = workbook.active
        mon_record = self.mon_id.id


        missing_components = []
        for row in worksheet.iter_rows(min_row=2, values_only=True):  # Adjust min_row based on your file structure
            try:
                # Skip rows with None or NA values
                if any(cell is None or cell == 'NA' for cell in row):
                    continue
                material_name, qty = row
                component = self.env['sos_material'].search([('part_no', '=', material_name)])
                line_model = self.env['sos_mon_line_material']
                min_line_model = self.env['sos_min_line_material']
                min_record = self.env['sos_min'].search([('mon_no', '=', mon_record)], limit=1)
                if component:
                    line_model.create({'mon_id': mon_record,
                    'component_id':component.id,
                    'quantity':qty
                    })
                    min_line_model.create({'min_id': min_record.id,
                    'component_id':component.id,
                    'quantity':qty
                    })
                else:
                    missing_components.append({'name': material_name, 'quantity': qty})
            except Exception as e:
                # Log the error and continue with the next row
                print(f"Error processing row {row}: {e}")
                continue


        # Implement your logic for handling missing components here
        if missing_components:
            # Log or create action for missing components
            return self.create_wizard_with_lines(missing_components, self.id)


        return {
                'type': 'ir.actions.client',
                'tag': 'reload'
    }
    @api.model
    def create_wizard_with_lines(self, missing_components, bulk_wizard_id):
        # Create line data for missing components
        line_data = [
        {
            'missing_component_name': component['name'],
            'missing_component_quantity': component['quantity']  # Assuming you have this field in your line model
        } for component in missing_components
        ]

        # Create the wizard and lines in one go
        wizard = self.env['mon_missing_component_wizard'].create({
            'missing_component_line_ids': [(0, 0, line) for line in line_data]
        })

        view_id = self.env.ref('sos_inventory.view_mon_missing_component_wizard_form').id
        return {
            'type': 'ir.actions.act_window',
            'name': 'Handle Missing Components',
            'view_mode': 'form',
            'res_model': 'mon_missing_component_wizard',
            'view_id': view_id,
            'target': 'new',
            'res_id': wizard.id,
            'context': {
            'default_mon_id': self.id
        }
        }
