#!/usr/bin/env python2

# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2019 NIWA & British Crown (Met Office) & Contributors.
#
# 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/>.

"""cylc gpanel [OPTIONS]

This is a cylc scan panel applet for monitoring running suites on a set of
hosts in GNOME 2.

To install this applet, run "cylc gpanel --install" and follow the instructions
that it gives you.

This applet can be tested using the --test option.

To customize themes, copy $CYLC_DIR/etc/gcylc.rc.eg to $HOME/.cylc/gcylc.rc and
follow the instructions in the file.

To configure default suite hosts, edit "[suite servers]scan hosts" in your
global.rc file."""

from optparse import OptionParser
import os
import sys
import warnings
warnings.filterwarnings('ignore', 'use the new', Warning)

sys.path.append(
    os.path.dirname(os.path.realpath(os.path.abspath(__file__))) + '/../lib/')
cylc_dir = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
if cylc_dir != os.getenv('CYLC_DIR', ''):
    os.environ['CYLC_DIR'] = cylc_dir

parser = OptionParser(__doc__)

parser.add_option("--compact",
                  help="Switch on compact mode at runtime.",
                  action="store_true", dest="compact")

parser.add_option("--install",
                  help="Install the panel applet.",
                  default=False,
                  action="store_true", dest="install")

parser.add_option("--test",
                  help="Run in a standalone window.",
                  default=False,
                  action="store_true", dest="test")

arglist = [a for a in sys.argv[1:] if not a.startswith("--oaf")]
(options, args) = parser.parse_args(arglist)

import cylc

cylc_dir = os.path.dirname(
    os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
if os.path.basename(cylc_dir).startswith("cylc-"):
    # If using the wrapper, reference 'cylc' rather than 'cylc-6.3.1'.
    cylc_alt_dir = os.path.join(os.path.dirname(cylc_dir), "cylc")
    if os.path.realpath(cylc_alt_dir) == os.path.realpath(cylc_dir):
        cylc_dir = cylc_alt_dir

if cylc_dir != os.getenv('CYLC_DIR', ''):
    os.environ['CYLC_DIR'] = cylc_dir

from cylc.gui.gpanel import ScanPanelApplet, run_in_window


def install_panel_applet():
    home = os.path.expanduser("~")
    dest_dir = os.path.join(home, ".bonobo")
    if not os.path.isdir(dest_dir):
        os.mkdir(dest_dir)
    for server_filename in ["cylc.server", "cylc-compact.server"]:
        source_file = os.path.join(cylc_dir, "etc", server_filename)
        dest_file = os.path.join(dest_dir, server_filename)
        f = open(source_file, "r")
        text = f.read().replace("$CYLC_DIR", cylc_dir)
        f.close()
        open(dest_file, "w").write(text)
        print dest_file, "created."
    print
    print """Further Instructions:
 * normal users - place this line in your ~/.profile file:
export BONOBO_ACTIVATION_PATH=$HOME/.bonobo
 * (sys)admin users - move the new cylc.server and cylc-compact.server
files into your /usr/lib/bonobo/servers/ directory, or equivalent.
 * After logging in and out, right-click within the GNOME 2 panel and
select "Add to Panel", then choose a Cylc Applet."""


def panel_applet_factory_compact(applet, _):
    my_panel_app = ScanPanelApplet(is_compact=True)
    applet.add(my_panel_app.get_widget())
    applet.show_all()
    return True


def panel_applet_factory(applet, _):
    my_panel_app = ScanPanelApplet()
    applet.add(my_panel_app.get_widget())
    applet.show_all()
    return True


if __name__ == "__main__":
    if options.test:
        run_in_window(options.compact)
    elif options.install:
        install_panel_applet()
    elif options.compact:
        import gnomeapplet
        gnomeapplet.bonobo_factory(
            "OAFIID:GNOME_CylcCompactMonitorFactory",
            gnomeapplet.Applet.__gtype__,
            "cylc gpanel compact", "0", panel_applet_factory_compact)
    else:
        import gnomeapplet
        gnomeapplet.bonobo_factory(
            "OAFIID:GNOME_CylcMonitorFactory",
            gnomeapplet.Applet.__gtype__,
            "cylc gpanel", "0", panel_applet_factory)
