# -*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.exceptions import UserError, ValidationError
from zeep import Client
import logging

_logger = logging.getLogger(__name__)


class ResCurrency(models.Model):
    _inherit = "res.currency"

    @api.model
    def get_exchange_rates(self):
        default_currency = self.env.ref('base.main_company').currency_id
        active_currencies = self.env['res.currency'].search([('active','=',True)])
        WSDLFILE = 'https://services.nbg.gov.ge/Rates/Service.asmx?wsdl'
        
        try:
            _server = Client(WSDLFILE)
            if default_currency.name == 'GEL':
                base_rate = 1.0
            else:
                base_rate = _server.service.GetCurrentRates(default_currency.name)[0].Rate
            date = _server.service.GetCurrentRates()[0].Date

            for currency in active_currencies:
                if currency.rate_ids.filtered(lambda r: r.name == fields.Date.today()):
                    continue
                if currency.name != 'GEL':
                    found_currency_obj = _server.service.GetCurrentRates(currency.name)
                    if found_currency_obj:
                        rate_obj = found_currency_obj[0]
                        rate_num = rate_obj.Rate
                        currency_amount = rate_obj.Quantity
                        if currency_amount and int(currency_amount) != 1:
                            rate_num = float(rate_num) / int(currency_amount)
                        if rate_num:
                            calculated_rate = float(base_rate) / float(rate_num)
                            calculated_rate = 1 / calculated_rate
                            currency.write({'rate_ids': [(0, 0, {'name': date, 'rate': calculated_rate})]})
                else:
                    currency.write({'rate_ids': [(0, 0, {'name': date, 'rate': float(base_rate)})]})
        except Exception as e:
            _logger.error(f"Failed to get echange rates. {e}")
