from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
import os

class PffftConan(ConanFile):
    name = "Pffft"
    version = "latest"
    license = "BSD"
    author = "Julien Pommier"
    url = "https://github.com/qno/conan-pffft"
    homepage = "https://bitbucket.org/jpommier/pffft"
    description = "PFFFT : a Pretty Fast FFT."

    settings = "os", "compiler", "build_type", "arch"

    options = {
        "shared": [True, False],
        "fPIC": [True, False]
        }
    default_options = {
        "shared": False,
         "fPIC": True
         }

    generators = "cmake"

    _pkg_name = "pffft"
    _libname = "pffft"

    def source(self):
        url = "https://bitbucket.org/jpommier/pffft/get/29e4f76ac53b.zip"
        self.output.info("Downloading {}".format(url))
        tools.get(url, sha256="bb10afba127904a0c6c553fa445082729b7d72373511bda1b12a5be0e03f318a")
        os.rename("jpommier-pffft-29e4f76ac53b",self._pkg_name)
        self._createCMakeLists()

    def configure(self):
        del self.settings.compiler.libcxx
        del self.options.fPIC
        if self.options.shared:
            raise ConanInvalidConfiguration("This library doesn't support shared lib compilation")

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

    def package(self):
        self.copy("*.h", dst="include", src=self._pkg_name)
        self.copy("*.lib", dst="lib", keep_path=False)
        self.copy("*.dll", dst="lib", keep_path=False)
        self.copy("*.so", dst="lib", keep_path=False)
        self.copy("*.dylib", dst="lib", keep_path=False)
        self.copy("*.a", dst="lib", keep_path=False)

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

    def _isVisualStudioBuild(self):
        return self.settings.os == "Windows" and self.settings.compiler == "Visual Studio"

    def _createCMakeLists(self):
        content = '''\
# THIS FILE WAS GENERATED BY CONAN RECIPE. DO NOT EDIT THIS FILE!
cmake_minimum_required(VERSION 3.5)
project(Pffft)

include(${{CMAKE_BINARY_DIR}}/conanbuildinfo.cmake)
conan_basic_setup()

set(LIBPFFFT "{}")
set(SOURCES pffft/pffft.c pffft/fftpack.c)
add_library(${{LIBPFFFT}} ${{SOURCES}})

if ("${{CMAKE_CXX_COMPILER_ID}}" MATCHES "^(GNU|Clang|AppleClang)$")
   target_compile_options (${{LIBPFFFT}} PRIVATE -msse4 -mfpmath=sse)
endif ()

if (MSVC)
   # _USE_MATH_DEFINES needed for M_PI
   target_compile_definitions (${{LIBPFFFT}} PRIVATE _USE_MATH_DEFINES)
endif ()

'''.format(self._libname)

        self.output.info("create CMakeLists.txt file")
        cmake_file = os.path.join(self._pkg_name, "CMakeLists.txt")
        f = open(cmake_file, "w+")
        f.write(content)
        f.close()
