import base64
from io import BytesIO
import tempfile
import os
from odoo import models, fields, _
from tbc_bank_integration_service_lib.client import TBCBankClient


class BankSettings(models.Model):
    _name = 'bank.settings'
    _description = 'Bank Integration Settings'

    bank_id = fields.Many2one('brosse.bank', string='Bank', required=True)
    wsdl_url = fields.Char(string='WSDL URL', required=True)
    cert_file_name = fields.Char(string='Certificate File Name', required=True)
    cert_file_path = fields.Binary(string='Certificate File', required=True, help="Upload your certificate file (.pfx)")
    cert_password = fields.Char(string='Certificate Password', required=True)
    username = fields.Char(string='Username', required=True)
    current_password = fields.Char(string='Current Password', required=True)
    nonce = fields.Char(string='Nonce', required=True)

    def get_request_object(self):
        config = self.env.ref('bross_bank_management.bank_api_configuration')
        cert_data = base64.b64decode(config.cert_file_path)
        cert_file_stream = BytesIO(cert_data)

        client = TBCBankClient(
            config.wsdl_url,
            cert_file_stream,
            config.cert_password,
            config.username,
            config.current_password
        )
        return client

    def test_api_connection(self):
        client = self.get_request_object()

        try:
            movement_id = '013762510743.2'
            movements_by_id = client.get_account_movements_by_id('111111', movement_id)
            message = _("Connection Test Successful!")
            message_type = 'success'
        except Exception as e:
            message = _("Connection Test Failed!")
            message_type = 'danger'
            _logger.error(e)

        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'message': message,
                'type': message_type,
                'sticky': False,
            }
        }