#
#  Sticky.rb
#  Stickies
#
#  Created by Laurent Sansonetti on 1/4/07.
#  Copyright (c) 2007 Apple Computer. All rights reserved.
#

class NoteReader < NSWindowController
  
  ib_outlet :contents  
  attr_accessor :action, :windowFrameAsString

  
  def noteNib
    @noteNib ||= NSNib.alloc.initWithNibNamed_bundle('Note', nil)
  end
  
  WINDOW_FRAME_KEY = 'windowFrameAsString'
  WINDOW_FRAME_STORAGE = 'noteWindow'
  
  def initWithAction(action)
    initWithWindowNibName("Note")
	@action=action
    setupNote
    self
  end
  
  def windowTitleForDocumentDisplayName(foo)
	return @action.name
  end
  
  def managedObjectContext
    @action.managedObjectContext
  end
  
  def managedObjectContext=
  end
  
  def close(sender)
	close
  end
  def performClose(sender)
	close
  end
  
  def windowShouldClose?(sender)
    return true
  end
  
  def textView_clickedOnLink_atIndex?(tv,link,index)
    return NSWorkspace.sharedWorkspace.openURL?(link)
  end
  
  # Set up the sticky's window from the sticky nib file
  def setupNote
    
	loadWindow
    window.setDelegate(self)
    window.setFrame_display( NSRectFromString(@action.noteWindow),true) if @action.noteWindow
    showWindow(self)
    
    # Register for KVO on the sticky's frame rect so that the window will redraw if we change the frame
    @action.objc_send :addObserver, self,
              :forKeyPath, WINDOW_FRAME_STORAGE,
              :options, NSKeyValueObservingOptionNew,
              :context, nil
  end

  def observeValueForKeyPath_ofObject_change_context(keyPath, object, change, context)
    # If the value of a sticky's frame changes in the managed object, we update the window to match
    return unless keyPath.to_s == WINDOW_FRAME_STORAGE
    val = change.objectForKey(NSKeyValueChangeNewKey)
    return unless val.is_a?(NSString)
    newFrame = NSRectFromString(val)
    # Don't setFrame if the frame hasn't changed; this prevents infinite recursion
    if window.frame != newFrame
      window.setFrame_display(newFrame, true)
    end
  end

  def awakeFromInsert
    super_awakeFromInsert
    noteWindow.instantiateNibWithOwner_topLevelObjects(self, nil)
    rememberWindowFrame # Need to get an initial value for the window size and ocation into the database.
    window.makeKeyAndOrderFront(self)
  end
  
  def show
    showWindow(self)
  end

  # Destroy the sticky
  def windowShouldClose(sender)
    @action.closeNoteReader
    true
  end

  def rememberWindowFrame
    @action.setValue_forKey(NSStringFromRect(window.frame), WINDOW_FRAME_STORAGE)
  end

  def windowDidMove(notification)
    rememberWindowFrame
  end
  
  def windowDidResize(notification)
    rememberWindowFrame
  end

=begin
- (void) dealloc
{
	if(stickyWindow) {
		[stickyWindow orderOut:self];
		[stickyWindow release];
    }
	[super dealloc];
}
=end
  
end
