//
//  AppDelegate.swift
//  writeas
//
//  Created by Matt Baer on 12/29/15.
//  Copyright © 2015 A Bunch Tell. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var vc: ViewController?

    @IBOutlet weak var nightModeItem: NSMenuItem!
    @IBOutlet weak var formatFontSerifItem: NSMenuItem!
    @IBOutlet weak var formatFontSansItem: NSMenuItem!
    @IBOutlet weak var formatFontMonoItem: NSMenuItem!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Set night mode state
        nightModeItem.state = Int(UserDefaults.standard.string(forKey: "night_mode_state") ?? String(NSOffState))!
        if nightModeItem.state == NSOnState {
            vc?.toggle(isNight: true)
        }

        // Set font
        let font = Preferences.getFont()
        if font == Preferences.PostFont.serif {
            formatFontSerifItem.state = NSOnState
            vc?.setFont(.serif)
        } else if font == Preferences.PostFont.sans {
            formatFontSansItem.state = NSOnState
            vc?.setFont(.sans)
        } else if font == Preferences.PostFont.mono {
            formatFontMonoItem.state = NSOnState
            vc?.setFont(.mono)
        }
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        vc?.saveDocument()
    }
    
    func applicationDidBecomeActive(_ notification: Notification) {
        if vc == nil {
            vc = NSApplication.shared().mainWindow?.contentViewController as? ViewController
        }
    }

    @IBAction func toggleNightMode(_ sender: NSMenuItem) {
        let isOff = sender.state == NSOffState
        vc?.toggle(isNight: isOff)
        sender.state = isOff ? NSOnState : NSOffState
        UserDefaults.standard.set(String(sender.state), forKey: "night_mode_state")
    }

    @IBAction func setFontSerif(_ sender: NSMenuItem) {
        deselectAllFonts()
        sender.state = NSOnState
        vc?.setFont(.serif)
        Preferences.setFont(.serif)
    }

    @IBAction func setFontSans(_ sender: NSMenuItem) {
        deselectAllFonts()
        sender.state = NSOnState
        vc?.setFont(.sans)
        Preferences.setFont(.sans)
    }

    @IBAction func setFontMono(_ sender: NSMenuItem) {
        deselectAllFonts()
        sender.state = NSOnState
        vc?.setFont(.mono)
        Preferences.setFont(.mono)
    }

    func deselectAllFonts() {
        formatFontSerifItem.state = NSOffState
        formatFontSansItem.state = NSOffState
        formatFontMonoItem.state = NSOffState
    }

    @IBAction func saveDocument(_ sender: AnyObject) {
        vc?.saveDocument()
    }

    @IBAction func publishDoc(_ sender: Any) {
        vc?.publish()
    }

    @IBAction func viewIncTextSize(_ sender: Any) {
        vc?.adjustTextSize(increment: true)
    }

    @IBAction func viewDecTextSize(_ sender: Any) {
        vc?.adjustTextSize(increment: false)
    }
}

