#!/usr/bin/env python3

#
# __init__.py
#
# Copyright (C) 2016 Christian Hergert <chergert@redhat.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

from gettext import gettext as _

import gi
import os

gi.require_version('Ide', '1.0')
gi.require_version('Template', '1.0')

from gi.repository import Ide
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Peas
from gi.repository import Template

def get_module_data_path(name):
    engine = Peas.Engine.get_default()
    plugin = engine.get_plugin_info('autotools_templates')
    data_dir = plugin.get_data_dir()
    return GLib.build_filenamev([data_dir, name])

class LibraryTemplateProvider(GObject.Object, Ide.TemplateProvider):
    def do_get_project_templates(self):
        return [LibraryProjectTemplate(), EmptyProjectTemplate()]

class AutotoolsTemplate(Ide.TemplateBase, Ide.ProjectTemplate):
    def __init__(self, id, name, icon_name, description, languages):
        super().__init__()
        self.id = id
        self.name = name
        self.icon_name = icon_name
        self.description = description
        self.languages = languages

    def do_get_id(self):
        return self.id

    def do_get_name(self):
        return self.name

    def do_get_icon_name(self):
        return self.icon_name

    def do_get_description(self):
        return self.description

    def do_get_languages(self):
        return self.languages

    def do_expand_async(self, params, cancellable, callback, data):
        task = Gio.Task.new(self, cancellable, callback)

        name = params['name'].get_string().lower()

        if 'path' in params:
            dir_path = params['path'].get_string();
        else:
            dir_path = name

        self.language = 'c'
        if 'language' in params:
            self.language = params['language'].get_string().lower()

        if self.language not in ('c', 'c++', 'vala'):
            task.return_error(GLib.Error("Language %s not supported" % self.language))
            return

        directory = Gio.File.new_for_path(dir_path)

        scope = Template.Scope.new()

        scope.get('template').assign_string(self.id)

        prefix = name if not name.endswith('-glib') else name[:-5]
        PREFIX = prefix.upper().replace('-','_')
        prefix_ = prefix.lower().replace('-','_')

        scope.get('name').assign_string(name)
        scope.get('name_').assign_string(name.lower().replace('-','_'))
        scope.get('NAME').assign_string(name.upper().replace('-','_'))

        scope.get('prefix').assign_string(prefix)
        scope.get('Prefix').assign_string(prefix.capitalize())
        scope.get('prefix_').assign_string(prefix_)
        scope.get('PREFIX').assign_string(PREFIX)

        scope.get('packages').assign_string("gio-2.0 >= 2.42")
        scope.get('major_version').assign_string('0')
        scope.get('minor_version').assign_string('1')
        scope.get('micro_version').assign_string('0')
        scope.get('enable_c').assign_boolean(True)
        scope.get('enable_cplusplus').assign_boolean(self.language == 'c++')
        scope.get('enable_i18n').assign_boolean(True)
        scope.get('enable_gtk_doc').assign_boolean(False)
        scope.get('enable_gobject_introspection').assign_boolean(True)
        scope.get('enable_vapi').assign_boolean(True)
        scope.get('enable_vala').assign_boolean(self.language == 'vala')
        scope.get('license').assign_string('/* license */')
        scope.get('translation_copyright').assign_string('Translation copyright holder')
        scope.get('language').assign_string(self.language)

        self.prepare_scope(scope)

        expands = {
            'name': name,
            'prefix': prefix,
        }

        files = {
            'resources/CONTRIBUTING.md':                'CONTRIBUTING.md',
            'resources/Makefile.am':                    'Makefile.am',
            'resources/NEWS':                           'NEWS',
            'resources/README.md':                      'README.md',
            'resources/autogen.sh':                     'autogen.sh',
            'resources/configure.ac':                   'configure.ac',
            'resources/git.mk':                         'git.mk',

            'resources/m4/Makefile.am':                 'm4/Makefile.am',
            'resources/m4/appstream-xml.m4':            'm4/appstream-xml.m4',
            'resources/m4/ax_append_compile_flags.m4':  'm4/ax_append_compile_flags.m4',
            'resources/m4/ax_append_flag.m4':           'm4/ax_append_flag.m4',
            'resources/m4/ax_check_compile_flag.m4':    'm4/ax_check_compile_flag.m4',
            'resources/m4/ax_check_link_flag.m4':       'm4/ax_check_link_flag.m4',
            'resources/m4/ax_compiler_vendor.m4':       'm4/ax_compiler_vendor.m4',
            'resources/m4/ax_compiler_flags_cxxflags.m4':'m4/ax_compiler_flags_cxxflags.m4',
            'resources/m4/ax_cxx_compile_stdcxx_11.m4': 'm4/ax_cxx_compile_stdcxx_11.m4',
            'resources/m4/ax_require_defined.m4':       'm4/ax_require_defined.m4',
            'resources/m4/glib-gettext.m4':             'm4/glib-gettext.m4',
            'resources/m4/gsettings.m4':                'm4/gsettings.m4',
            'resources/m4/intltool.m4':                 'm4/intltool.m4',
            'resources/m4/introspection.m4':            'm4/introspection.m4',
            'resources/m4/libtool.m4':                  'm4/libtool.m4',
            'resources/m4/pkg.m4':                      'm4/pkg.m4',
            'resources/m4/vala.m4':                     'm4/vala.m4',
            'resources/m4/vapigen.m4':                  'm4/vapigen.m4',

            'resources/data/Makefile.am':               'data/Makefile.am',

            'resources/po/LINGUAS':                     'po/LINGUAS',
            'resources/po/Makevars':                    'po/Makevars',
            'resources/po/POTFILES.in':                 'po/POTFILES.in',
        }
        self.prepare_files(files)

        modes = { 'resources/autogen.sh': 0o750 }
        self.prepare_file_modes(modes)

        for src,dst in files.items():
            path = get_module_data_path(src)
            destination = directory.get_child(dst % expands)
            self.add_path(path, destination, scope, modes.get(src, 0))

        self.expand_all_async(cancellable, self.expand_all_cb, task)

    def do_expand_finish(self, result):
        return result.propagate_boolean()

    def expand_all_cb(self, obj, result, task):
        try:
            self.expand_all_finish(result)
            task.return_boolean(True)
        except Exception as exc:
            print(exc)
            task.return_error(GLib.Error(repr(exc)))

    def prepare_scope(self, scope):
        pass

    def prepare_files(self, files):
        pass

    def prepare_file_modes(self, modes):
        pass

class LibraryProjectTemplate(AutotoolsTemplate):
    def __init__(self):
        super().__init__(
            'shared-library',
            _("Shared Library"),
            'pattern-library',
            _("Create a new autotools project with a shared library"),
            ['C', 'C++', 'Vala']
         )

    def prepare_files(self, files):
        files['resources/data/package.pc.in'] = 'data/%(name)s.pc.in'

        if self.language in ('c', 'c++'):
            files['resources/src/Makefile.shared-library-c'] = 'src/Makefile.am'
            files['resources/src/package.h'] = 'src/%(name)s.h'
            files['resources/src/package-version.h.in'] = 'src/%(prefix)s-version.h.in'

        elif self.language == 'vala':
            files['resources/src/Makefile.shared-library-vala'] = 'src/Makefile.am'
            files['resources/src/package.vala'] = 'src/%(prefix)s.vala'


class EmptyProjectTemplate(AutotoolsTemplate):
    def __init__(self):
        super().__init__(
            'empty',
            _("Empty Project"),
            # it would be nice to have a different icon here.
            'pattern-library',
            _("Create a new empty autotools project"),
            ['C', 'C++', 'Vala']
         )

