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

import datetime
from dateutil.relativedelta import relativedelta

from odoo import api, fields, models


class CurrencyConfigSettings(models.TransientModel):
    _inherit = 'res.config.settings'

    company_id = fields.Many2one(comodel_name="res.company", string='Company')
    currency_interval_unit = fields.Selection(related="company_id.currency_interval_unit",)
    currency_provider = fields.Selection(related="company_id.currency_provider",)
    currency_next_execution_date = fields.Date(related="company_id.currency_next_execution_date")

    @api.onchange('currency_interval_unit')
    def onchange_currency_interval_unit(self):
        if self.currency_interval_unit == 'daily':
            next_update = relativedelta(days=+1)
        elif self.currency_interval_unit == 'weekly':
            next_update = relativedelta(weeks=+1)
        elif self.currency_interval_unit == 'monthly':
            next_update = relativedelta(months=+1)
        else:
            self.currency_next_execution_date = False
            return
        self.currency_next_execution_date = datetime.date.today() + next_update

    @api.multi
    def update_currency_rates(self):
        companies = self.env['res.company'].search([])
        companies.update_currency_rates()
