#!/usr/bin/python3
"""
  Openbox Key Editor
  
  This file is a part of Openbox Key Editor

  Initial version from 2009 to 2018 is under MIT License
  Copyright (C) 2009 nsf <no.smile.face@gmail.com>
  v1.1 - Code migrated from PyGTK to PyGObject
         github.com/stevenhoneyman/obkey
  v1.2pre1 - solve a minor bug on copy-paste bug
  v1.2pre  - 19.06.2016 - i structured presentation of actions...
 
  Change made from 2018 is under GPL License
  Copyright (C) 2018  luffah <luffah@runbox.com>
  v1.2     - 24.02.2018 - i slightly refactored the code - i wanted change more dynamic
  v1.3     - 05.06.2018 - i wanted it more fun, sorting, and searching
         github.com/luffah/obkey

  MIT License

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

  GPL License

  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/>.
"""

import sys
import os
import re
from obkey_parts import PropertyTable, KeyTable, ActionList, OpenboxConfig, Gtk


def get_rcfile():
    """return the rcfile from args or find it"""
    ret = None
    rcfileregex = re.compile(r'.*\.xml.*')
    rcfiles = list(filter(rcfileregex.match, sys.argv))
    if rcfiles:
        ret = rcfiles[0]
    else:
        try:
            import psutil
            # get rc file from current running openbox
            for pdesc in psutil.process_iter():
                proc = pdesc.as_dict(attrs=['pid', 'name', 'cmdline'])
                if proc['name'] == 'openbox':
                    ob_params = proc['cmdline']
                    param_name = '--config-file'
                    if param_name in ob_params:
                        ret = ob_params[ob_params.index(param_name) + 1]
        except ImportError:
            pass
    return ret or (os.getenv("HOME") + "/.config/openbox/rc.xml")


def die(window, application_data=None):
    """kill the application"""
    if application_data:
        pass
    if window:
        Gtk.main_quit()


def view():
    """Initialize obkey window"""

    obkeyconf = OpenboxConfig()
    obkeyconf.load(get_rcfile())

    window = Gtk.Window()

    window.set_title('obkey')
    window.connect("destroy", die)

    width = window.get_preferred_width()[1]
    height = window.get_preferred_height()[1]

    propertytable = PropertyTable()
    actionlist = ActionList(propertytable)
    keytable = KeyTable(actionlist, obkeyconf, window)

    window.set_default_size(max(width,800), max(height,600))
    verticalbox = Gtk.VPaned()
    #print((verticalbox.__dict__))
    verticalbox.set_size_request(300,-1)
    verticalbox.pack1(propertytable.widget, True, True)
    verticalbox.pack2(actionlist.widget, True, True)

    horizontalbox = Gtk.HPaned()
    horizontalbox.pack1(keytable.widget, True, False)
    horizontalbox.pack2(verticalbox, False, False)
    window.add(horizontalbox)
    window.show_all()
    keytable.view.grab_focus()
    window.set_default_size(height, width)
    Gtk.main()


OPT_DESC = {
    'rc.xml': ['OpenBox configuration file to edit'],
    '--help|-h': ['Show this help'],
}

def usage():
    """usage"""
    opt = []
    for (optname, optdesc) in list(OPT_DESC.items()):
        tmpopt = [optname]
        if len(optdesc) > 1: # params
            tmpopt.extend(list(optdesc[1].keys()))
        opt.append(' '.join(tmpopt))
    print((
        'Usage : ' + sys.argv[0] + ' ' +
        ' '.join(
            [('[%s]' % a) for a in opt]
            )
        ))
    for (optname, optdesc) in list(OPT_DESC.items()):
        print("{0:<14s} {1:s}".format(optname, optdesc[0]))
        tmpopt = [optname]
        if len(optdesc) > 1: # params
            for (param, pdesc) in list(optdesc[1].items()):
                print("  {0:<14s} {1:s}".format(param, pdesc))

if __name__ == '__main__':
    help_re = re.compile('--help|-h')
    help_matched = list(filter(help_re.match, sys.argv))
    if help_matched:
        usage()
    else:
        view()
