#!/usr/bin/python3
# -*- coding:Utf-8 -*-
"""
MyNotes - Sticky notes/post-it
Copyright 2016-2018 Juliette Monsel <j_4321@protonmail.com>

MyNotes 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.

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


Main
"""


import os
import sys
import traceback
import signal
from tkinter import Tk
from tkinter.ttk import Style
from mynoteslib.constants import save_config, PIDFILE
from mynoteslib.app import App
from mynoteslib.messagebox import showerror
import logging
from mynoteslib.version import __version__
import argparse

# parse command line arguments
parser = argparse.ArgumentParser(description=_("MyNotes - Post-it system tray app"),
                                 epilog=_("Report bugs to https://github.com/j4321/MyNotes/issues."))
parser.add_argument('-V', '--version', help=_('show version and exit'), action='store_true')
group = parser.add_mutually_exclusive_group()
group.add_argument('-H', '--hide-all', help=_('hide all notes'), action='store_true')
group.add_argument('-S', '--show-all', help=_('show all notes'), action='store_true')
args = parser.parse_args()

if args.version:
    print('mynotes ' + __version__)
    sys.exit()

pid = str(os.getpid())

# check weher MyNotes is already running
if os.path.isfile(PIDFILE):
    with open(PIDFILE) as fich:
        old_pid = fich.read().strip()
    if os.path.exists("/proc/%s" % old_pid):
        with open("/proc/%s/cmdline" % old_pid) as file:
            cmdline = file.read()
        if 'mynotes' in cmdline:    # MyNotes is already runnning
            if args.show_all:
                # send signal to mynotes to show all notes
                os.kill(int(old_pid), signal.SIGUSR1)
                sys.exit()
            elif args.hide_all:
                # send signal to mynotes to hide all notes
                os.kill(int(old_pid), signal.SIGUSR2)
                sys.exit()
            else:
                # MyNotes is already runnning
                root = Tk()
                root.withdraw()
                s = Style(root)
                s.theme_use("clam")
                showerror(_("Error"), _("MyNotes is already running, if not delete {pidfile}.").format(pidfile=PIDFILE))
                sys.exit()
        else:
            # it is an old .pid file
            os.remove(PIDFILE)
    else:
        # it is an old pid file
        os.remove(PIDFILE)
open(PIDFILE, 'w').write(pid)

try:
    app = App(args)
    app.mainloop()
except Exception as e:
    showerror(_("Error"), str(type(e)), traceback.format_exc(), True)
finally:
    try:
        app.save()
        save_config()
        os.unlink(PIDFILE)
        logging.shutdown()
    except Exception:
        pass
