#!/usr/bin/env python2
# -*- coding: UTF-8 -*-
#
#       cherrytree
#
#       Copyright 2009-2019 Giuseppe Penone <giuspen@gmail.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, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

import os, sys, __builtin__

try:
    import argparse
    ARGPARSE_OK = True
except:
    ARGPARSE_OK = False

def win32_unicode_argv():
    """Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
    strings.

    Versions 2.x of Python don't support Unicode in sys.argv on
    Windows, with the underlying Windows API instead replacing multi-byte
    characters with '?'.
    """

    from ctypes import POINTER, byref, cdll, c_int, windll
    from ctypes.wintypes import LPCWSTR, LPWSTR

    GetCommandLineW = cdll.kernel32.GetCommandLineW
    GetCommandLineW.argtypes = []
    GetCommandLineW.restype = LPCWSTR

    CommandLineToArgvW = windll.shell32.CommandLineToArgvW
    CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
    CommandLineToArgvW.restype = POINTER(LPWSTR)

    cmd = GetCommandLineW()
    argc = c_int(0)
    argv = CommandLineToArgvW(cmd, byref(argc))
    if argc.value > 0:
        # Remove Python executable and commands if present
        start = argc.value - len(sys.argv)
        return [argv[i].encode('utf-8') for i in # use 'utf-8', so gtk2 doesn't give warnings about argv
                xrange(start, argc.value)]
            
def f_main(args):
    if hasattr(sys, 'frozen'):
        # windows, py2exe
        SHARE_PATH = os.path.dirname(sys.executable)
        MODULES_PATH = os.path.join(SHARE_PATH, 'modules')
    else:
        SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
        if os.path.isfile(os.path.join(SCRIPT_DIR, 'glade', 'cherrytree.png'))\
        and os.path.isfile(os.path.join(SCRIPT_DIR, 'modules', 'main.py')):
            # not installed
            SHARE_PATH = SCRIPT_DIR
            MODULES_PATH = os.path.join(SCRIPT_DIR, 'modules')
        else:
            # installed
            SHARE_PATH = os.path.join(os.path.dirname(SCRIPT_DIR), 'share')
            MODULES_PATH = os.path.join(SHARE_PATH, 'cherrytree', 'modules')
    __builtin__.SHARE_PATH = SHARE_PATH
    sys.path.insert(0, MODULES_PATH)
    import main
    main.main(args)


if sys.platform.startswith("win"):
    sys.argv = win32_unicode_argv()

if ARGPARSE_OK:
    parser = argparse.ArgumentParser()
    parser.add_argument('filepath', nargs='?', help='Optional CherryTree Document to Open')
    parser.add_argument("-n", "--node", help="Node Name to Focus")
    parser.add_argument("-x", "--export_to_html_dir", help="Export to HTML at Specified Directory")
    parser.add_argument("-t", "--export_to_txt_dir", help="Export to Text at Specified Directory")
    parser.add_argument("-p", "--export_to_pdf_path", help="Export to PDF at Specified Path")
    parser.add_argument("-w", "--export_overwrite", action="store_true", help="Overwrite Existing Export")
    args = parser.parse_args()
else:
    class CherryArgs:
        node = None
        filepath = None
        export_to_html_dir = None
        export_to_txt_dir = None
        export_to_pdf_path = None
        export_overwrite = False
    args = CherryArgs
    if len(sys.argv) > 1:
        if sys.argv[1] == "-h":
            print "cherrytree [filepath [-n nodename] [-x export_to_html_dir] [-t export_to_txt_dir] [-p export_to_pdf_path] [-w]]"
            exit(0)
        else: args.filepath = sys.argv[1]
        if len(sys.argv) > 3:
            if sys.argv[2] == "-n": args.node = sys.argv[3]
            elif sys.argv[2] == "-x": args.export_to_html_dir = sys.argv[3]
            elif sys.argv[2] == "-t": args.export_to_txt_dir = sys.argv[3]
            elif sys.argv[2] == "-p": args.export_to_pdf_path = sys.argv[3]
            elif sys.argv[2] == "-w": args.export_overwrite = True
f_main(args)
