//
//  AppDelegate.swift
//  ipbc-Client
//
//  Created by Gerrit Linnemann on 09.09.15.
//  Copyright (c) 2015 Adawim UG (haftungsbeschränkt). All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!
    
    let popover = NSPopover()
    var eventMonitor: EventMonitor?
    let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-2)

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
        
        WebserviceClient.sharedInstance     // to init
        
        // Icon
        if let button = statusItem.button {
            button.image = NSImage(named: "statusbar-icon")
            button.action = Selector("togglePopover:")
        }
        
        popover.contentViewController = MainViewController(nibName: "MainViewController", bundle: nil)
        
        
        // EventMonitor
        eventMonitor = EventMonitor(mask: [.LeftMouseDownMask, .RightMouseDownMask]) { [unowned self] event in
            if self.popover.shown {
                self.closePopover(event)
            }
        }
        eventMonitor?.start()
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }

    // MARK: Popover
    
    func showPopover(sender: AnyObject?) {
        if let button = statusItem.button {
            popover.showRelativeToRect(button.bounds, ofView: button, preferredEdge: NSRectEdge.MinY)
        }
    }
    
    func closePopover(sender: AnyObject?) {
        popover.performClose(sender)
    }
    
    func togglePopover(sender: AnyObject?) {
        if popover.shown {
            closePopover(sender)
        } else {
            showPopover(sender)
        }
    }
}

