# Copyright 2015 The Meson development team

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

'''This module provides helper functions for Gnome/GLib related
functionality such as gobject-introspection and gresources.'''

import build
import os, sys
import subprocess
from coredata import MesonException
import mlog

class GnomeModule:

    def compile_resources(self, state, args, kwargs):
        cmd = ['glib-compile-resources', '@INPUT@', '--generate']
        if 'source_dir' in kwargs:
            d = os.path.join(state.build_to_src, state.subdir, kwargs.pop('source_dir'))
            cmd += ['--sourcedir', d]
        if 'c_name' in kwargs:
            cmd += ['--c-name', kwargs.pop('c_name')]
        cmd += ['--target', '@OUTPUT@']
        kwargs['command'] = cmd
        output_c = args[0] + '.c'
        output_h = args[0] + '.h'
        kwargs['input'] = args[1]
        kwargs['output'] = output_c
        target_c = build.CustomTarget(args[0]+'_c', state.subdir, kwargs)
        kwargs['output'] = output_h
        target_h = build.CustomTarget(args[0] + '_h', state.subdir, kwargs)
        return [target_c, target_h]
    
    def generate_gir(self, state, args, kwargs):
        if len(args) != 1:
            raise MesonException('Gir takes one argument')
        girtarget = args[0]
        while hasattr(girtarget, 'held_object'):
            girtarget = girtarget.held_object
        if not isinstance(girtarget, (build.Executable, build.SharedLibrary)):
            raise MesonException('Gir target must be an executable or shared library')
        pkgstr = subprocess.check_output(['pkg-config', '--cflags', 'gobject-introspection-1.0'])
        pkgargs = pkgstr.decode().strip().split()
        ns = kwargs.pop('namespace')
        nsversion = kwargs.pop('nsversion')
        libsources = kwargs.pop('sources')
        girfile = '%s-%s.gir' % (ns, nsversion)
        depends = [girtarget]

        scan_command = ['g-ir-scanner', '@INPUT@']
        scan_command += pkgargs
        scan_command += ['--namespace='+ns, '--nsversion=' + nsversion, '--warn-all',
                         '--output', '@OUTPUT@']

        extra_args = kwargs.pop('extra_args', [])
        if not isinstance(extra_args, list):
            extra_args = [extra_args]
        scan_command += extra_args

        for incdirs in girtarget.include_dirs:
            for incdir in incdirs.get_incdirs():
                scan_command += ['-I%s' % os.path.join(state.environment.get_source_dir(), incdir)]

        if 'link_with' in kwargs:
            link_with = kwargs.pop('link_with')
            if not isinstance(link_with, list):
                link_with = [link_with]
            for link in link_with:
                lib = link.held_object
                scan_command += ['-l%s' % lib.name]
                if isinstance(lib, build.SharedLibrary):
                    scan_command += ['-L%s' %
                            os.path.join(state.environment.get_build_dir(),
                                lib.subdir)]
                    depends.append(lib)

        if 'includes' in kwargs:
            includes = kwargs.pop('includes')
            if isinstance(includes, str):
                scan_command += ['--include=%s' % includes]
            elif isinstance(includes, list):
                scan_command += ['--include=%s' % inc for inc in includes]
            else:
                raise MesonException('Gir includes must be str or list')
        if state.global_args.get('c'):
            scan_command += ['--cflags-begin']
            scan_command += state.global_args['c']
            scan_command += ['--cflags-end']
        if kwargs.get('symbol_prefix'):
            sym_prefix = kwargs.pop('symbol_prefix')
            if not isinstance(sym_prefix, str):
                raise MesonException('Gir symbol prefix must be str')
            scan_command += ['--symbol-prefix=%s' % sym_prefix]
        if kwargs.get('identifier_prefix'):
            identifier_prefix = kwargs.pop('identifier_prefix')
            if not isinstance(identifier_prefix, str):
                raise MesonException('Gir identifier prefix must be str')
            scan_command += ['--identifier-prefix=%s' % identifier_prefix]
        if kwargs.get('export_packages'):
            pkgs = kwargs.pop('export_packages')
            if isinstance(pkgs, str):
                scan_command += ['--pkg-export=%s' % pkgs]
            elif isinstance(pkgs, list):
                scan_command += ['--pkg-export=%s' % pkg for pkg in pkgs]
            else:
                raise MesonException('Gir export packages must be str or list')

        deps = None
        if 'dependencies' in kwargs:
            deps = kwargs.pop('dependencies')
            if not isinstance (deps, list):
                deps = [deps]
            for dep in deps:
                girdir = dep.held_object.get_variable ("girdir")
                if girdir: