# pylint: disable=g-backslash-continuation
# Copyright 2021 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import tempfile
import unittest

from src.test.py.bazel import test_base
from src.test.py.bazel.bzlmod.test_utils import BazelRegistry


class BazelModuleTest(test_base.TestBase):

  def setUp(self):
    test_base.TestBase.setUp(self)
    self.registries_work_dir = tempfile.mkdtemp(dir=self._test_cwd)
    self.main_registry = BazelRegistry(
        os.path.join(self.registries_work_dir, 'main'))
    self.main_registry.createCcModule('A', '1.0') \
        .createCcModule('A', '1.1') \
        .createCcModule('B', '1.0', {'A': '1.0'}, {'A': 'com_foo_bar_a'}) \
        .createCcModule('B', '1.1', {'A': '1.1'}) \
        .createCcModule('C', '1.1', {'A': '1.1', 'B': '1.1'})
    self.ScratchFile(
        '.bazelrc',
        [
            # In ipv6 only network, this has to be enabled.
            # 'startup --host_jvm_args=-Djava.net.preferIPv6Addresses=true',
            'build --experimental_enable_bzlmod',
            'build --registry=' + self.main_registry.getURL(),
            'build --verbose_failures',
        ])

  def writeMainProjectFiles(self):
    self.ScratchFile('WORKSPACE')
    self.ScratchFile('A.patch', [
        '--- a/a.cc',
        '+++ b/a.cc',
        '@@ -1,6 +1,6 @@',
        ' #include <stdio.h>',
        ' #include "a.h"',
        ' void hello_a(const std::string& caller) {',
        '-    std::string lib_name = "A@1.0";',
        '+    std::string lib_name = "A@1.0 (locally patched)";',
        '     printf("%s => %s\\n", caller.c_str(), lib_name.c_str());',
        ' }',
    ])
    self.ScratchFile('BUILD', [
        'cc_binary(',
        '  name = "main",',
        '  srcs = ["main.cc"],',
        '  deps = [',
        '    "@A//:lib_a",',
        '    "@B//:lib_b",',
        '  ],',
        ')',
    ])
    self.ScratchFile('main.cc', [
        '#include "a.h"',
        '#include "b.h"',
        'int main() {',
        '    hello_a("main function");',
        '    hello_b("main function");',
        '}',
    ])

  def testSimple(self):
    self.ScratchFile('WORKSPACE')
    self.ScratchFile('MODULE.bazel', [
        'bazel_dep(name = "A", version = "1.0")',
    ])
    self.ScratchFile('BUILD', [
        'cc_binary(',
        '  name = "main",',
        '  srcs = ["main.cc"],',