#
# Copyright 3D Control Systems, Inc. All Rights Reserved 2017-2019. Built in San Francisco.
#
# This software is distributed under commercial non-GPL license for personal, educational,
# corporate or any other use. The software as a whole or any parts of that are prohibited
# for distribution and/or use without obtaining license from 3D Control Systems, Inc.
#
# If you do not have the license to use this software, please delete all software files
# immediately and contact sales to obtain the license: sales@3dprinteros.com.
# If you are unsure about the licensing please contact directly our sales: sales@3dprinteros.com.

import sys
import os


# fix of broken paths for windows
if not sys.path:
    sys.path = []
path = os.getcwd()
if path not in sys.path:
    sys.path.insert(0, path)


import tray_common
try:
    import wx
    import wx.adv
except:
    print('No WX module found')
    sys.exit(1)


class TaskBarIcon(wx.adv.TaskBarIcon):

    @staticmethod
    def create_menu_item(menu, label, function):
        item = wx.MenuItem(menu, -1, label)
        menu.Bind(wx.EVT_MENU, function, id=item.GetId())
        menu.Append(item)
        return item

    def __init__(self):
        super(TaskBarIcon, self).__init__()
        self.set_icon(tray_common.ICON_PATH)
        self.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN, self.on_show_status)
        self.status_checker = tray_common.StatusChecker(self.ShowBalloon)

    def CreatePopupMenu(self):
        menu = wx.Menu()
        self.create_menu_item(menu, 'Open browser tab', self.on_tab_open)
        self.create_menu_item(menu, 'Show status', self.on_show_status)
        if self.status_checker.notifications:
            self.create_menu_item(menu, 'Disable notifications', self.on_disable_notifications)
        else:
            self.create_menu_item(menu, 'Enable notifications', self.on_enable_notifications)
        self.create_menu_item(menu, 'Exit', self.on_exit)
        return menu

    def set_icon(self, path):
        icon = wx.Icon(path)
        self.SetIcon(icon, tray_common.APP_NAME)

    def on_disable_notifications(self, _):
        self.status_checker.toggle_notifications(False)
        self.CreatePopupMenu()

    def on_enable_notifications(self, _):
        self.status_checker.toggle_notifications(True)
        self.CreatePopupMenu()

    def on_show_status(self, _):
        self.status_checker.show_status_balloons()

    def on_exit(self, _):
        tray_common.stop_app()
        self.status_checker.stop()
        wx.CallAfter(self.Destroy)

    def on_tab_open(self, _):
        tray_common.open_browser_tab()


def run():
    app = wx.App()
    TaskBarIcon()
    app.MainLoop()


if __name__ == '__main__':
    run()
