# .ycm_extra_conf.py for single file C/C++ programs (as a fallback default)
import os
import ycm_core

# Attention:
# Relative file paths will be expanded relative to the editing file.
# File path not starting with '/' will be expanded.

flags_c = [
    '-Wall',
    '-Wextra',
    # '-Werror',
    '-Wno-variadic-macros',
    #'-DNDEBUG',
    '-x', 'c',
    '-std=gnu11',
#    '-isystem', '/usr/local/include',
#    '-isystem', '/usr/include',
    '-I', 'include',
    '-I', '../include',
]

flags_cpp = [
    '-Wall',
    '-Wextra',
    # '-Werror',
    '-Wno-variadic-macros',
    '-fexceptions',
    #'-DNDEBUG',
    '-x', 'c++',
    '-std=gnu++14',
    '-stdlib=libstdc++',
#    '-isystem', '/usr/include/c++/6.2.1',
#    '-isystem', '/usr/include/c++/6.2.1/x86_64-unknown-linux-gnu',
#    '-isystem', '/usr/include/c++/6.2.1/backward',
#    '-isystem', '/usr/local/include',
#    '-isystem', '/usr/include',
    '-I', 'include',
    '-I', '../include',
]

database = None

HEADER_EXTENSIONS = ['.h', '.hxx', '.hpp', '.hh']
SOURCE_EXTENSIONS = ['.cpp', '.cxx', '.cc', '.c', '.m', '.mm']


def MakeRelativePathsInFlagsAbsolute(flags, working_directory):
    if not working_directory:
        return flags
    new_flags = []
    make_next_absolute = False
    path_flags = ['-isystem', '-I', '-iquote', '--sysroot=', '-include']
    for flag in flags:
        new_flag = flag

        if make_next_absolute:
            make_next_absolute = False
            if not flag.startswith('/'):
                new_flag = os.path.join(working_directory, flag)

        for path_flag in path_flags:
            if flag == path_flag:
                make_next_absolute = True
                break
            if flag.startswith(path_flag):
                path = flag[len(path_flag):]
                new_flag = path_flag + os.path.join(working_directory, path)
                break

        if new_flag:
            new_flags.append(new_flag)

    return new_flags


def TryGetDatabase(filename):
    global database
    # At this time it's still filename, but we'll take its basedir later.
    dirname = filename
    while dirname != '/':
        dirname = os.path.dirname(dirname)
        if os.path.exists(os.path.join(dirname, "compile_commands.json")):
            database = ycm_core.CompilationDatabase(dirname)
            return


def GetCompilationInfoForFile(filename):
    # The compilation_commands.json generated by CMake does not have entries
    # for header files. So we do our best by asking the db for flags for a
    # corresponding source file, if any. If one exists, the flags for that file
    # should be good enough.
    basename, extension = os.path.splitext(filename)
    if extension in HEADER_EXTENSIONS:
        for new_extension in SOURCE_EXTENSIONS:
            replacement_file = basename + new_extension
            if os.path.exists(replacement_file):
                compilation_info = \
                    database.GetCompilationInfoForFile(replacement_file)
                if compilation_info.compiler_flags_:
                    return compilation_info
        return None
    return database.GetCompilationInfoForFile(filename)


def FlagsForFile(filename):
    TryGetDatabase(filename)
    if database:
        # Bear in mind that compilation_info.compiler_flags_ does NOT return a
        # python list, but a "list-like" StringVec object
        compilation_info = GetCompilationInfoForFile(filename)
        if not compilation_info:
            return None
        final_flags = MakeRelativePathsInFlagsAbsolute(
            compilation_info.compiler_flags_,
            compilation_info.compiler_working_dir_
        )
    else:
        # We don't have compilation database. Use the default flags!
        extension = os.path.splitext(filename)[1]
        # For header files, make a best guess if it's C or C++.
        if extension == '.c' or \
                extension == '.h' and os.path.exists(filename[:-2] + '.c'):
            flags = flags_c
        else:
            flags = flags_cpp
        relative_to = os.path.dirname(filename)
        final_flags = MakeRelativePathsInFlagsAbsolute(flags, relative_to)

    return {
        'flags': final_flags,
        'do_cache': True
    }
