# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from unittest.mock import patch

from odoo.exceptions import ValidationError
from odoo.tests.common import Command, tagged, TransactionCase


@tagged('at_install', '-post_install')  # LEGACY at_install
class TestCompany(TransactionCase):

    def test_check_active(self):
        """Tests the ability to archive a company whether or not it still has active users.
        Tests an archived user in an archived company cannot be unarchived
        without changing its company to an active company."""
        company = self.env['res.company'].create({'name': 'foo'})
        user = self.env['res.users'].create({
            'name': 'foo',
            'login': 'foo',
            'company_id': company.id,
            'company_ids': company.ids,
        })

        # The company cannot be archived because it still has active users
        with self.assertRaisesRegex(ValidationError, 'The company foo cannot be archived'):
            company.action_archive()

        # The company can be archived because it has no active users
        user.action_archive()
        company.action_archive()

        # The user cannot be unarchived because it's default company is archived
        with self.assertRaisesRegex(ValidationError, 'Company foo is not in the allowed companies'):
            user.action_unarchive()

        # The user can be unarchived once we set another, active, company
        main_company = self.env.ref('base.main_company')
        user.write({
            'company_id': main_company.id,
            'company_ids': main_company.ids,
        })
        user.action_unarchive()

    def test_logo_check(self):
        """Ensure uses_default_logo is properly (re-)computed."""
        company = self.env['res.company'].create({'name': 'foo'})

        self.assertTrue(company.logo, 'Should have a default logo')
        self.assertTrue(company.uses_default_logo)
        company.partner_id.image_1920 = False
        # No logo means we fall back to another default logo for the website route -> uses_default
        self.assertTrue(company.uses_default_logo)
        company.partner_id.image_1920 = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
        self.assertFalse(company.uses_default_logo)

    def test_create_branch_with_default_parent_id(self):
        branch = self.env['res.company'].with_context(default_parent_id=self.env.company.id).create({'name': 'Branch Company'})
        self.assertFalse(branch.partner_id.parent_id)

    def test_correct_order_of_company(self):
        """Ensure that companies are correctly ordered in a hierarchy"""
        Company = self.env['res.company']
        main_company = self.env.ref('base.main_company')
        self.assertEqual(len(main_company), 1, "main company do not exists")

        second_company = Company.create({
            'name': main_company.name + '2',
            'sequence': main_company.sequence + 999,
        })
        companies = Company.search([('id', 'in', [main_company.id, second_company.id])])

        # If main_company will not have sequence then the child company will be before the main_company
        # If the main_company has sequence (default 10) then it will be before the child company due to order by name
        self.assertListEqual(
            companies.ids,
            [main_company.id, second_company.id],
            "Companies are not in the correct order",
        )

    def test_write_company_root_delegated_field_names(self):
        self.env['res.company'].with_context(default_parent_id=self.env.company.id).create({'name': 'foo'})
        new_currency = self.env['res.currency'].create({
            'name': 'AAA',
            'symbol': 'AAA',
            'rate_ids': [Command.create({'name': '2009-09-09', 'rate': 1})]
        })
        with patch('odoo.addons.base.models.res_company.ResCompany._get_company_root_delegated_field_names', return_value=["currency_id", "zip"]):
            self.env.company.write({'currency_id': new_currency.id, 'zip': '12345'})
