from conan import ConanFile
from conan.tools.cmake import CMake, CMakeDeps, CMakeToolchain, cmake_layout
from conan.tools.files import copy, get, rmdir, export_conandata_patches
import os

required_conan_version = ">=1.60.0 <2.0 || >=2.0.5"


class HunspellRecipe(ConanFile):
    name = "hunspell"
    package_type = "library"
    user = "aurora"

    # Optional metadata
    homepage = "http://hunspell.github.io/"
    author = "Daniil Markevich <d.markevich@omp.ru>"
    url = "https://gitverse.ru/auroraos/mirror_hunspell"
    license = "MPL-1.1", "GPL-2.0-or-later", "LGPL-2.1-or-later"
    description = "Hunspell is a free spell checker and morphological analyzer library."
    topics = ("hunspell", "spell checker", "morphological")

    # Binary configuration
    settings = "os", "compiler", "build_type", "arch"
    options = {
        "shared": [True, False]
    }
    default_options = {
        "shared": True
    }

    def layout(self):
        cmake_layout(self)

    def export_sources(self):
        export_conandata_patches(self)
        # TODO: Remove once PR is merged: https://github.com/hunspell/hunspell/pull/704/
        copy(self, "CMakeLists.txt", src=self.recipe_folder, dst=self.export_sources_folder)

    def source(self):
        get(self, **self.conan_data["sources"][self.version], strip_root=True)
        h = os.path.join(self.source_folder, "src", "hunspell", "hunvisapi.h")
        os.remove(h)

    def generate(self):
        deps = CMakeDeps(self)
        deps.generate()
        tc = CMakeToolchain(self)
        tc.variables["CONAN_hunspell_VERSION"] = self.version
        tc.cache_variables["BUILD_SHARED_LIBS"] = self.options.shared
        tc.generate()

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

    def package(self):
        copy(self, "LICENSE", src=self.source_folder,
             dst=os.path.join(self.package_folder, "licenses"))
        cmake = CMake(self)
        cmake.install()
        rmdir(self, os.path.join(self.package_folder, "lib/cmake"))

    def package_info(self):
        self.cpp_info.libs = ["hunspell"]
        if not self.options.shared:
            self.cpp_info.defines = ["HUNSPELL_STATIC"]
