//
//  CCSciView.m
//  sci4osx_test
//
//  Created by serg on 7/21/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//


#import <Carbon/Carbon.h>

#import "CCSciView.h"
#include "CRSciWindow.h"

@implementation CCSciView


-(id)initWithFrame:(NSRect)frame
{
  self= [super initWithFrame:frame];
  if (self)
  {
    _sciWindow= new CRSciWindow();
    
    _sciNSWindow = [[NSWindow alloc] initWithWindowRef:_sciWindow->init()];
    _sciWindow->createEditor(_sciNSWindow);
    
    [_sciNSWindow useOptimizedDrawing:true];
    [self setPostsFrameChangedNotifications: YES];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(frameChanged:)
                                                 name:NSViewFrameDidChangeNotification 
                                               object:self];    
  }
  return self;
}


- (void)viewDidUnhide
{
  NSLog(@"unhide");
  //xx not working
  [_sciNSWindow orderFrontRegardless];
}


- (void)viewDidHide
{
  NSLog(@"hide");
    //xx not working
  [_sciNSWindow orderOut: nil];
}


- (void)viewWillDraw
{
  if (![_sciNSWindow parentWindow])
  {
    [[self window] addChildWindow:_sciNSWindow ordered:NSWindowAbove];
    [self updateSize];
    [_sciNSWindow orderFrontRegardless];
  }
  else
    [self updateSize];
}


- (void)frameChanged:(NSNotification*)notification
{  
  if ([_sciNSWindow parentWindow])
  {
    [self updateSize];
  }
}



- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver: self];
  
  delete _sciWindow;
  [_sciNSWindow release];
  [super dealloc];
}



- (void)setString:(NSString*)string
{
  _sciWindow->view().set_text([string UTF8String]);
  /*
  const int pos = _sciWindow->sendEditor(SCI_GETCURRENTPOS);
  _sciWindow->sendEditor(SCI_SETTEXT, 0, (sptr_t)[string UTF8String]);
  _sciWindow->sendEditor(SCI_GOTOPOS, pos);
  _sciWindow->sendEditor(SCI_SCROLLCARET);
   */
}


- (void)setEditable:(BOOL)flag
{
  NSLog(@"setEditable");
}


- (void)updateSize
{
  NSRect frame = [self frame];
  
  frame.origin= [self convertPoint: frame.origin toView:nil];
//  frame.origin= [[self window] convertBaseToScreen: frame.origin];

  NSWindow* sciWindow = *_sciWindow;
  [sciWindow setFrame:frame display:true];
  // workaround for resize issue: to force window redraw after resize
  {
    Rect r;
    GetWindowBounds(*_sciWindow, kWindowContentRgn, &r);
    SetWindowBounds(*_sciWindow, kWindowContentRgn, &r);
  }
}

- (void)windowWillClose:(NSNotification *)notification
{
  _sciWindow->dispose();
}
@end
