from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout, CMakeDeps
from conan.tools.files import copy
from conan.tools.scm import Git
from conan.tools.files import patch
import os


class valhallaRecipe(ConanFile):
    name = "valhalla"
    package_type = "library"
    user = "aurora"

    # Optional metadata
    license = "MIT"
    author = "Vladislav Larionov <vladislav.larionov@fruct.org>"
    url = "https://gitverse.ru/auroraos/mirror_valhalla"
    description = "Open Source Routing Engine for OpenStreetMap.\n" \
         "This is an adapted version of Valhala for the mfw plugin from \n" \
         "https://gitlab.com/omprussia/libraries/mfw-offline-routing/-/blob/master/vendors/valhalla.cmake?ref_type=heads"
    topics = ("valhalla", "maps", "routing", "OpenStreetMap")

    # Binary configuration
    settings = "os", "compiler", "build_type", "arch"
    options = {"shared": [True, False]}
    default_options = {"shared": True}
    exports = "CMakeLists.txt", '*.patch'

    def layout(self):
        cmake_layout(self)

    def requirements(self):
        self.requires("protobuf/3.18.3@aurora")
        self.requires("boost/1.85.0@aurora", transitive_headers=True)

    def source(self):
        git = Git(self)
        git.clone(url="https://github.com/valhalla/valhalla.git", target=".")
        commit = self.conan_data["sources"][self.version]["commit"]
        git.checkout(commit=commit)
        git.run("submodule update --init --recursive")

    def generate(self):
        deps = CMakeDeps(self)
        deps.generate()
        tc = CMakeToolchain(self)
        protobuf_package_folder = str(self.dependencies["protobuf/3.18.3@aurora"].package_folder)
        tc.cache_variables["Protobuf_package_path"] = protobuf_package_folder
        tc.generate()

    def build(self):
        self._copy_and_apply_patches()
        cmake = CMake(self)
        cmake.configure()
        cmake.build()

    def _copy_and_apply_patches(self):
        copy(self, "CMakeLists.txt", src=os.path.join(self.recipe_folder), dst=self.source_folder)
        adapt_conanfile_patch_file = os.path.join(self.recipe_folder, "patches", "adapt_conanfile_to_conan2.patch")
        patch(self, patch_file=adapt_conanfile_patch_file)
        boost_patch_file = os.path.join(self.recipe_folder, "patches", "boost.patch")
        patch(self, patch_file=boost_patch_file)

    def package(self):
        cmake = CMake(self)
        cmake.install()

    def package_info(self):
        self.cpp_info.libs = ["valhalla"]
