import os
import textwrap
import re

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


class mozjpegConan(ConanFile):
    name = "mozjpeg"
    package_type = "library"
    user = "aurora"
    
    # Optional metadata
    license = "BSD-2-Clause"
    author = "Angelica Volkova <angelica.volkova@fruct.org>"
    url = "https://gitverse.ru/auroraos/mirror_mozjpeg"
    description = "Improved JPEG encoder."
    topics = ("web-performance", "mozjpeg", "libjpeg", "image-optimization", "jpeg-encoder")    

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

    def requirements(self):
        self.requires("libpng/1.6.44@aurora")
        self.requires("zlib/1.3.1@aurora")

    def export_sources(self):
        export_conandata_patches(self)

    def layout(self):
        cmake_layout(self)

    def source(self):
        get(self, **self.conan_data["sources"][self.version], strip_root=True)
        apply_conandata_patches(self)
    
    def generate(self):
        deps = CMakeDeps(self)

        deps.set_property("libpng", "cmake_file_name", "PNG")
        deps.set_property("zlib", "cmake_file_name", "ZLIB")
        deps.generate()
        
        tc = CMakeToolchain(self)

        tc.variables["ENABLE_SHARED"] = True
        tc.variables["ENABLE_STATIC"] = False
        tc.variables["PNG_SUPPORTED"] = True
        tc.variables["BUILD_TESTING"] = False
        tc.variables["WITH_JAVA"] = False
        tc.variables["WITH_ARITH_ENC"] = False
        tc.variables["WITH_ARITH_DEC"] = False
        tc.generate()

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

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

    def package_info(self):
        self.cpp_info.set_property("cmake_file_name", "mozjpeg")
        self.cpp_info.set_property("cmake_target_name", "mozjpeg::mozjpeg")
        
        self.cpp_info.components["jpeg"].libs = ["jpeg"]
        self.cpp_info.components["turbojpeg"].libs = ["turbojpeg"]
        
        self.cpp_info.components["jpeg"].set_property("cmake_target_name", "mozjpeg::jpeg")
        self.cpp_info.components["turbojpeg"].set_property("cmake_target_name", "mozjpeg::turbojpeg")
        
        self.cpp_info.components["jpeg"].requires.append("libpng::libpng")
        self.cpp_info.components["jpeg"].requires.append("zlib::zlib")
            
        self.cpp_info.libs = ["jpeg", "turbojpeg"]
