//
//  TDLWindowController.swift
//  ToDoList
//
//  Created by narita on 2017/09/12.
//  Copyright © 2017年 narita. All rights reserved.
//

import Cocoa

class TDLWindowController: MINTLWindowController
{
    // MARK: - class methods
    
    // MARK: - init methods
    
    // MARK: - dealloc
    
    // MARK: - NSCopying, hash, isEqual:
    
    // MARK: - NSCoding methods
    
    // MARK: - restorableState methods
    
    override func encodeRestorableState(with coder: NSCoder)
    {
        super.encodeRestorableState(with: coder)

        coder.encode(self.arrayController?.selectionIndexes, forKey: "indexes")
    }

    override func restoreState(with coder: NSCoder)
    {
        super.restoreState(with: coder)

        if let theIndexSet = coder.decodeObject(forKey: "indexes") as! NSIndexSet?
        {
            // 一回イベントループを回った後でしか、selectionを設定できないようなので遅延実行させる。
            // ToDo: どこにフックをかけるべきか、もう一度検討すること
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2)
            {
                self.arrayController?.setSelectionIndexes(theIndexSet as IndexSet)
            }
        }
    }
    
    
    // MARK: - life cycle methods
    
    override func windowDidLoad()
    {
        super.windowDidLoad()
        
        self.shouldCascadeWindows = true
                
        self.window!.titleVisibility = .hidden
        
        arrayController?.sortDescriptors = [NSSortDescriptor.init(key:"sortOrder", ascending:true)]
    }
    
    // MARK: - action methods
    
    // MARK: - event handling methods
    
    // MARK: - drawing methods
    
    // MARK: - delegate/datasource methods
    
    // MARK: - accessor methods (in pairs)
    
    @IBOutlet var arrayController: NSArrayController?

    // MARK: - Utility methods
    
    @objc func windowWillReturnUndoManager(_ window: NSWindow) -> UndoManager?
    {
        if let theDocument = self.document as! TDLDocument?
        {
            return theDocument.managedObjectContext!.undoManager
        }
        
        return nil
    }
}
