import os
import shutil
from conans import ConanFile, CMake, AutoToolsBuildEnvironment, tools, VisualStudioBuildEnvironment
from conans.tools import os_info, SystemPackageTool, download, untargz, replace_in_file, unzip


class LibpqxxConan(ConanFile):
    name = "libpqxx"
    version = "5.0.1"
    settings = "os", "compiler", "build_type", "arch"
    description = "Conan package for the libpqxx library"
    url = "https://github.com/jgsogo/conan-libpqxx"
    license = "https://github.com/jtv/libpqxx/blob/master/COPYING"

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

    @property
    def pq_source_dir(self):
        return os.path.abspath("libpqxx-%s" % self.version)

    def requirements(self):
        self.requires.add("postgresql/v9.6.5@jgsogo/stable")

    def system_requirements(self):
        if os_info.is_linux:
            if os_info.with_apt:
                installer = SystemPackageTool()
                if not self.options.disable_documentation:
                    installer.install("doxygen")

    def source(self):
        if self.version == 'master':
            raise NotImplementedError("Compilation of master branch not implemented")
        else:
            url = "https://github.com/jtv/libpqxx/archive/{}.tar.gz".format(self.version)
            zip_name = 'libpqxx.tar.gz'
            download(url, zip_name)
            untargz(zip_name)
            os.unlink(zip_name)

    def build(self):
        if self.settings.os == "Linux" or self.settings.os == "Macos":
            self.run("ls -la {}/bin".format(self.deps_cpp_info["postgresql"].rootpath))
            options = "--with-postgres-include={}".format(os.path.join(self.deps_cpp_info["postgresql"].rootpath, "include"))
            options += " --with-postgres-lib={}".format(os.path.join(self.deps_cpp_info["postgresql"].rootpath, "lib"))

            if self.options.disable_documentation:
                options += " --disable-documentation"

            env = AutoToolsBuildEnvironment(self)
            env.vars["PATH"] = ':'.join([env.vars.get("PATH", ""), os.path.join(self.deps_cpp_info["postgresql"].rootpath, "bin")])
            with tools.environment_append(env.vars):
                with tools.chdir(self.pq_source_dir):
                    self.output.info(options)
                    self.run("echo $PATH")
                    self.run("./configure {}".format(options))
                    self.run("make")
        else:
            self.windows_build()

    def package(self):
        self.copy("pqxx/*", dst="include", src=os.path.join(self.pq_source_dir, "include"), keep_path=True)
        self.copy(pattern="COPYING", dst="licenses", src=self.pq_source_dir, ignore_case=True, keep_path=False)

        if self.settings.os == "Linux":
            # if shared:
            # self.copy(pattern="*.so*", dst="lib", src=os.path.join(self.FOLDER_NAME, "lib", ".libs"))
            self.copy("*.a", dst="lib", src=os.path.join(self.pq_source_dir, "src", ".libs"))
        elif self.settings.os == "Windows":
            self.copy("*.lib", dst="lib", src=os.path.join(self.pq_source_dir, "lib"))
            self.copy("*.bin", dst="bin", src=os.path.join(self.pq_source_dir, "lib"))

    def package_info(self):
        if self.settings.os == "Linux":
            self.cpp_info.libs = ["pqxx",]
        elif self.settings.os == "Windows":
            base_name = "libpqxx"
            if not self.options.shared:
                base_name += "_static"
            self.cpp_info.libs = [base_name, ]

    def windows_build(self):
        # Follow instructions in https://github.com/jtv/libpqxx/blob/master/win32/INSTALL.txt
        common_file = os.path.join(self.pq_source_dir, 'win32', 'common')
        with open(common_file, "w") as f:
            f.write('PGSQLSRC="{}"\n'.format(self.deps_cpp_info["postgresql"].rootpath))
            f.write('PGSQLINC=$(PGSQLSRC)\include\n')
            f.write('LIBPQINC=$(PGSQLSRC)\include\n')

            f.write('LIBPQPATH=$(PGSQLSRC)\lib\n')
            f.write('LIBPQDLL=libpq.dll\n')
            f.write('LIBPQLIB=libpq.lib\n')

            f.write('LIBPQDPATH=$(PGSQLSRC)\lib\n')
            f.write('LIBPQDDLL=libpq.dll\n')
            f.write('LIBPQDLIB=libpq.lib\n')

        target_dir = os.path.join(self.pq_source_dir, 'include', 'pqxx')
        with tools.chdir(os.path.join(self.pq_source_dir, 'config', 'sample-headers', 'compiler', 'VisualStudio2013', 'pqxx')):
            shutil.copy('config-internal-compiler.h', target_dir + "/")
            shutil.copy('config-public-compiler.h', target_dir + "/")

        vcvars = tools.vcvars_command(self.settings)
        self.run(vcvars)
        env = VisualStudioBuildEnvironment(self)
        with tools.environment_append(env.vars):
            with tools.chdir(self.pq_source_dir):
                target = "DLL" if self.options.shared else "STATIC"
                target += str(self.settings.build_type).upper()
                command = 'nmake /f win32/vc-libpqxx.mak %s' % target
                self.output.info(command)
                self.run(command)

@@ -1617,96 +1617,8 @@
 s%22:%0A
-            self.run(%22ls -la %7B%7D/bin%22.format(self.deps_cpp_info%5B%22postgresql%22%5D.rootpath))%0A
     
@@ -2020,140 +2020,8 @@
 lf)%0A
-            env.vars%5B%22PATH%22%5D = ':'.join(%5Benv.vars.get(%22PATH%22, %22%22), os.path.join(self.deps_cpp_info%5B%22postgresql%22%5D.rootpath, %22bin%22)%5D)%0A
     
@@ -2147,32 +2147,111 @@
     
-self.output.info(options
+add_path = %22export PATH=$PATH:%7B%7D%22.format(os.path.join(self.deps_cpp_info%5B%22postgresql%22%5D.rootpath, %22bin%22)
 )%0A  
@@ -2277,24 +2277,27 @@
 elf.
-run(%22echo $PATH%22
+output.info(options
 )%0A  
@@ -2324,16 +2324,22 @@
 lf.run(%22
+%7B%7D && 
 ./config
@@ -2353,16 +2353,26 @@
 .format(
+add_path, 
 options)

configure with add path