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

import Cocoa

class MainViewController: NSViewController {
    
    @IBOutlet weak var btnQuit: NSButton!
    @IBOutlet weak var btnRegister: NSButton!
    @IBOutlet weak var btnSave: NSButton!
    @IBOutlet weak var btnCancel: NSButton!
    @IBOutlet weak var lblCurrentIP: NSTextField!
    @IBOutlet weak var txtName: NSTextField!
    @IBOutlet weak var txtToken: NSTextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "observeUserIPHasChanged", name: Constants.Notification.NF_IP_HAS_CHANGED, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "observeNetworkAvailable", name: Constants.Notification.NF_NETWORK_AVAILABLE, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "observeNetworkNotAvailable", name: Constants.Notification.NF_NETWORK_NOT_AVAILABLE, object: nil)
        
        self.lblCurrentIP.stringValue = NSUserDefaults.standardUserDefaults().stringForKey(Constants.UserDefaults.PERSIST_LAST_USERS_IP) ?? ""
        
        let defaults = NSUserDefaults.standardUserDefaults()
        if let udHost = defaults.stringForKey(Constants.UserDefaults.HOST) {
            txtName.stringValue = udHost
        }
        if let udToken = defaults.stringForKey(Constants.UserDefaults.TOKEN) {
            txtToken.stringValue = udToken
        }
        
        if !WebserviceClient.sharedInstance.getIsNetworkAvailable() {
            lblCurrentIP.stringValue = "No internet connection!"
        }
    }
    
    // MARK: Actions
    
    @IBAction func actionQuit(sender: NSButton) {
        NSApplication.sharedApplication().terminate(self)
    }
    
    @IBAction func actionOpenRegister(sender: NSButton) {
        print("Not implemented yet")
    }
    
    @IBAction func actionSaveSettings(sender: NSButton) {
        let defaults = NSUserDefaults.standardUserDefaults()
        
        defaults.setObject(txtName.stringValue, forKey: Constants.UserDefaults.HOST)
        defaults.setObject(txtToken.stringValue, forKey: Constants.UserDefaults.TOKEN)
        
        NSNotificationCenter.defaultCenter().postNotificationName(Constants.Notification.NF_DATA_USERDATA_HAS_CHANGED, object: nil)
    }
    
    // MARK: Observer functions
    
    func observeUserIPHasChanged() {
        let newIP = NSUserDefaults.standardUserDefaults().stringForKey(Constants.UserDefaults.PERSIST_LAST_USERS_IP) ?? ""
        lblCurrentIP.stringValue = newIP
    }
    
    func observeNetworkAvailable() {
        observeUserIPHasChanged()
    }
    
    func observeNetworkNotAvailable() {
        lblCurrentIP.stringValue = "Network not reachable."
    }
}
