##############################################################################
#
#    Accounting Periods, for Odoo
#    Copyright (C) 2020 XCG Consulting <http://odoo.consulting>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from odoo import fields, models


class AccountChartTemplate(models.Model):
    """Build periods when loading accounting data for a new company.
    """

    _inherit = "account.chart.template"

    def _load(self, sale_tax_rate, purchase_tax_rate, company):
        """ Installs this chart of accounts on the current company, replacing
        the existing one if it had already one defined. If some accounting
        entries had already been made, this function fails instead, triggering
        a UserError.

        Also, note that this function can only be run by someone with
        administration rights.

        Override this method defined in the "account" module:
        * Build periods when loading accounting data for a new company.
        """

        ret = super(AccountChartTemplate, self)._load(
            sale_tax_rate, purchase_tax_rate, company
        )

        end_date = fields.Date.today().replace(
            day=company.fiscalyear_last_day,
            month=int(company.fiscalyear_last_month or "12"),
        )
        year_str = str(end_date.year)

        self.env["account.fiscalyear"].create(
            {
                "code": year_str,
                "company_id": company.id,
                "date_stop": end_date,
                "name": year_str,
            }
        ).create_period()

        return ret