#!/usr/bin/env python

# ----------------------------------------------------------------------
#  Author: Roberto Cavada <roboogle@gmail.com>
#
#  Copyright (C) 2007-2015 by Roberto Cavada
#
#  gtkmvc3 is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser General Public
#  License as published by the Free Software Foundation; either
#  version 2 of the License, or (at your option) any later version.
#
#  gtkmvc3 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
#  Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public
#  License along with this library; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor,
#  Boston, MA 02110, USA.
#
#  For more information on gtkmvc3 see <https://github.com/roboogle/gtkmvc3>
#  or email to the author Roberto Cavada <roboogle@gmail.com>.
#  Please report bugs to <https://github.com/roboogle/gtkmvc3/issues>
#  or to <roboogle@gmail.com>.
# ----------------------------------------------------------------------


# checks for gtkmvc3
try:
    import gtkmvc3
except:
    # use the local installation
    import os.path; import sys
    top_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
    sys.path = [top_dir] + sys.path
    import gtkmvc3

gtkmvc3.require("1.0.0")

from gtkmvc3.progen.model import ProgenModel, set_gui_log, set_shell_log
from gtkmvc3.progen.templates import VERSION
import sys
# --------------------

req_options = ("name",)
def process_options(args):
    m = {}
    if len(args) == 0:
        raise ValueError("No options given: run with option 'help'")
    for a in args:
        kv = a.split("=")
        if len(kv) > 2:
            raise ValueError("Invalid option: %s" % a)
        if len(kv) == 1:
            k, v = (kv[0], "yes")
        else: k, v = kv
        if v.lower() == "no":
            v = False
        elif v.lower() == "yes":
            v = True
        m[k] = v

    return m


def check_options(m):
    if "gui" in m:
        return
    for o in req_options:
        if o not in m:
            raise ValueError("Required option '%s' has not been specified" % o)


def fix_options(m): # fixes missing options
    if "gui" not in m:
        m['gui'] = "win32" in sys.platform.lower()
    if not ("gui" in m or "author" in m):
        m['author'] = "Bug Producer"


def print_banner():
    print("This is the gtkmvc3 Project Generator version %s" % ".".join(VERSION))


def print_help():
    print("Attributes can be specified in the form: attr=value")
    print('For example: author="Roberto Cavada"')
    print("Boolean attributes can be specified in the form attr[=yes|no]")
    print("For example: gui")
    print("Attributes and their default values are:")

    m = ProgenModel()

    _vals = {None: "",
             True: "yes",
             False: "no", }
    for a, v in ((a, getattr(m,a)) for a in m.get_properties()):
        print('\t%s"%s"' % (a.ljust(20), _vals.get(v, "")))

    print("\nBoolean option 'gui' has a default value that depends on the hosting platform")
    print("Required attributes are:")
    print("\t", " ".join(req_options))
    print()


def run_gui(model):
    from gi.repository import Gtk
    from gtkmvc3.progen.ctrl import ProgenCtrl
    from gtkmvc3.progen.view import ProgenView

    v = ProgenView()
    c = ProgenCtrl(model, v)

    set_gui_log(v['tv_res'].get_buffer())
    Gtk.main()


def run_shell(model):
    set_shell_log()
    try:
        model.generate_project()
    except ValueError as e:
        print("Error:" + str(e))


def main(attributes):
    pm = ProgenModel()

    for k in attributes:
        setattr(pm, k, attributes[k])

    if attributes['gui']:
        run_gui(pm)
    else:
        run_shell(pm)


if __name__ == "__main__":
    print_banner()
    try:
        attr = process_options(sys.argv[1:])
        fix_options(attr)
        check_options(attr)
    except Exception as e:
        print(e)
        sys.exit(1)

    if any(a in attr for a in "help -h --help".split()):
        print_help()
        sys.exit(1)

    main(attr)
