import os, glob
from conans import ConanFile, CMake, tools


class SmartScreenSDKConan(ConanFile):
    python_requires = "aac-sdk-tools/1.0"
    python_requires_extend = "aac-sdk-tools.BaseSdkDependency"

    name = "smart-screen-sdk"
    version = "2.9.2"
    settings = "os", "compiler", "build_type", "arch"
    generators = "cmake", "cmake_find_package", "pkg_config"
    exports_sources = "CMakeLists.txt", "patches/*"

    _source_subfolder = "source_subfolder"

    build_requires = ["pkgconf/1.7.3"]

    @property
    def default_channel(self):
        return "dev"

    def source(self):
        tools.get(f"https://github.com/alexa/alexa-smart-screen-sdk/archive/v{self.version}.tar.gz")
        os.rename(f"alexa-smart-screen-sdk-{self.version}", self._source_subfolder)

    def configure(self):
        self.settings.compiler.cppstd = "11"
        if self.settings.os == "Android":
            # Android does not support libraries with version extension (libssl.so.1.1)
            # so used static version off openssl for Android
            self.options["openssl"].shared = False

    def requirements(self):
        self.requires(f"avs-device-sdk/1.26.0@{self.user}/{self.channel}")

    def _configure_cmake(self):
        cmake = CMake(self)
        if self.settings.os == "Android":
            cmake.definitions["ANDROID"] = "OFF"  # this is not a mistake!
        cmake.configure(source_folder=self._source_subfolder)
        return cmake

    def _apply_patches(self):
        for filename in sorted(glob.glob("patches/*.patch")):
            self.output.info(f"applying patch: {filename}")
            tools.patch(base_path=self._source_subfolder, patch_file=filename)

    def build(self):
        self._apply_patches()
        # CMake does not always check the current build directory for packages.
        # Append cwd to PKG_CONFIG_PATH explicitly so that the .pc files generated by
        # pkg_config generator can be found.
        with tools.environment_append({"PKG_CONFIG_PATH": [os.getcwd()]}):
            cmake = self._configure_cmake()
            cmake.build()

    def package(self):
        cmake = self._configure_cmake()
        if self.settings.build_type == "Release":
            tools.mkdir(self.package_folder)
            # install stripped result
            cmake.build(target="install/strip")
        else:
            cmake.install()

    def package_info(self):
        self.cpp_info.names["pkg_config"] = "AlexaSmartScreenSDK"
        self.cpp_info.libs = tools.collect_libs(self)
