#!/usr/bin/env python

import os
import sys
import Utils

VERSION = "0.2.1"
VERSION_MAJOR_MINOR =  ".".join(VERSION.split(".")[0:2])
APPNAME = "clinica"

top = '.'
out = '_build_'

def options (opt):
    opt.load ('compiler_cc glib2 gnu_dirs')

def put_config_h_in (ctx, destination):
    
    # Config.h for libclinica
    ctx.define ("GETTEXT_PACKAGE", APPNAME)
    ctx.define('PACKAGE', APPNAME)
    ctx.define('PACKAGE_NAME', APPNAME)
    ctx.define('PACKAGE_STRING', APPNAME + '-' + VERSION)
    ctx.define('PACKAGE_VERSION', APPNAME + '-' + VERSION)

    ctx.define('VERSION', VERSION)
    ctx.define('VERSION_MAJOR_MINOR', VERSION_MAJOR_MINOR)

    ctx.write_config_header (os.path.join (destination, "config.h"))


def configure(ctx):
    ctx.load ('compiler_cc gnu_dirs glib2 intltool vala')
    ctx.check_vala (min_version = (0,12,0))

    # Some definitions
    ctx.check_cfg(package='glib-2.0', uselib_store='GLIB',
                   atleast_version='2.14.0', mandatory=True, args='--cflags --libs')
    ctx.check_cfg(package='gobject-2.0', uselib_store='GOBJECT',
                   atleast_version='2.14.0', mandatory=True, args='--cflags --libs')
    ctx.check_cfg(package='gtk+-3.0', uselib_store='GTK+',
                   atleast_version='2.10.0', mandatory=True, args='--cflags --libs')
    ctx.check_cfg(package='sqlite3', uselib_store='SQLITE',
                   atleast_version='3.0', mandatory=True, args='--cflags --libs')
    ctx.check_cfg(package='gee-1.0', uselib_store='GEE',
                   atleast_version='0.5', mandatory=True, args='--cflags --libs')
    ctx.check_cfg(package='libpeas-1.0', uselib_store='PEAS',
                   atleast_version='0.7.0', mandatory=True, args='--cflags --libs')
    ctx.check_cfg(package='libpeas-gtk-1.0', uselib_store='PEASGTK',
                   atleast_version='0.7.0', mandatory=True, args='--cflags --libs')

    ctx.find_program ('glib-compile-schemas', var='GLIB_COMPILE_SCHEMAS')
    ctx.find_program ('g-ir-compiler', var = 'G_IR_COMPILER')

    ctx.env.append_value ('VALAFLAGS', '-g')

    put_config_h_in (ctx, "libclinica")
    put_config_h_in (ctx, "clinica")
    put_config_h_in (ctx, "plugins")

    ctx.env.append_value ('CFLAGS', '-g -DHAVE_CONFIG_H -include config.h'.split ())

def build(bld):
    bld.add_subdirs('libclinica')
    bld.add_subdirs('clinica')
    bld.add_subdirs('plugins')

    # Translations
    bld (
        features = 'intltool_po', 
        podir = 'po',
        appname = 'clinica'
        )

    # Install data files
    topdir = bld.path.find_dir (top)
    bld.install_files ('${PREFIX}/share/clinica', topdir.ant_glob ('ui/*'),
                       relative_trick = True)
    bld.install_files ('${PREFIX}/share/clinica', topdir.ant_glob ('ui/icons/*'),
                       relative_trick = True)

    # Install the help
    help_dir = bld.path.find_dir ("help")
    bld.install_files ('${PREFIX}/share/gnome/help/clinica',
                       help_dir.ant_glob ('**/*.page'), relative_trick = True,
                       cwd = help_dir)
    bld.install_files ('${PREFIX}/share/gnome/help/clinica',
                       help_dir.ant_glob ('**/figures/*'), relative_trick = True,
                       cwd = help_dir)

    # Install the applications shortcut
    bld.install_files ('${PREFIX}/share/applications',
                       'clinica.desktop')

    # And the icons
    bld.install_files ('${PREFIX}/share/pixmaps',
                       'ui/icons/clinica.svg')

    # ..and the man documentation
    bld.install_files ('${PREFIX}/share/man/man1', 'doc/clinica.1')

def update_potfile_list (ctx):
    """Update the file POTFILES.in"""
    source_files = map (lambda x : os.path.join ("libclinica", x),
                        filter (lambda x : x.endswith (".vala") or x.endswith (".c"),
                                os.listdir ("libclinica")))
    source_files += map (lambda x : os.path.join ("clinica", x),
                         filter (lambda x : x.endswith (".vala"),
                                 os.listdir ("clinica")))
    source_files += map (lambda x : os.path.join ("ui", x),
                         filter (lambda x : x.endswith (".glade"),
                                 os.listdir ("ui")))
    with open ("po/POTFILES.in", "w") as handle:
        handle.write ("[encoding: UTF-8]\n")
        handle.write ("\n".join (source_files))

    print("""POTFILES.in has been regenerated, you may want to run intltool-update on the po files.
For example: cd po && intltool-udpate it
""")
        
def run(ctx):
    from waflib import Options
    Options.commands = [ 'build', '__do_run' ] + Options.commands

def __do_run (ctx):
    ctx.exec_command ("LD_LIBRARY_PATH=./_build_/libclinica ./_build_/clinica/clinica")

def debug (ctx):
    ctx.exec_command ("LD_LIBRARY_PATH=./_build_/libclinica gdb --args ./_build_/clinica/clinica")

def update_po (ctx):
    # Get the list of languages 
    with open("po/LINGUAS") as handle:
        content = handle.read()
    languages = filter (lambda x : len(x) == 2 and x.strip()[0] != '#', content.split("\n"))
    os.chdir ("po")
    ctx.exec_command("intltool-update -p -g clinica")
    for code in languages:
        ctx.exec_command("intltool-update -g clinica %s" % code)
