/*
SRFindController.m

Author: Makoto Kinoshita

Copyright 2004-2006 The Shiira Project. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted 
provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions 
  and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of 
  conditions and the following disclaimer in the documentation and/or other materials provided 
  with the distribution.

THIS SOFTWARE IS PROVIDED BY THE SHIIRA PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE SHIIRA PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

#import "SRBrowserController.h"
#import "SRFindController.h"
#import "SRPageController.h"

#import "SRMenu.h"

// Frame auto save name
NSString*   SRFindPanelFrameAutoSaveName = @"SRFindPanelFrameAutoSaveName";

@implementation SRFindController

//--------------------------------------------------------------//
#pragma mark -- Initialize --
//--------------------------------------------------------------//

+ (id)sharedInstance
{
    static SRFindController*    _sharedInstance = nil;
    if (!_sharedInstance) {
        _sharedInstance = [[SRFindController alloc] init];
    }
    
    return _sharedInstance;
}

- (id)init
{
    self = [super initWithWindowNibName:@"FindPanel"];
    if (!self) {
        return nil;
    }
    
    return self;
}

- (void)windowDidLoad
{
    // Configure window
    HMPanel*    panel;
    panel = (HMPanel*)[self window];
    [panel setPassMenuValidationToDelegate:YES];
    if (![panel frameAutosaveName]) {
        [panel setFrameAutosaveName:SRFindPanelFrameAutoSaveName];
    }
    
    // Hide text field
    [_notFoundTextField setHidden:YES];
}

//--------------------------------------------------------------//
#pragma mark -- String value --
//--------------------------------------------------------------//

- (NSString*)stringValue
{
    return [_findTextField stringValue];
}

- (void)setStringValue:(NSString*)string
{
    [_findTextField setStringValue:string];
}

//--------------------------------------------------------------//
#pragma mark -- Actions --
//--------------------------------------------------------------//

- (void)closeWindowAction:(id)sender
{
    [[self window] performClose:sender];
}

- (void)findOnDirection:(BOOL)direction closeWindow:(BOOL)flag
{
    // Get main window controller
    NSWindowController* windowController;
    windowController = [[NSApp mainWindow] windowController];
    if (!windowController) {
        return;
    }
    
    // Get find text
    NSString*   string;
    string = [_findTextField stringValue];
    if (!string || [string length] == 0) {
        return;
    }
    
    // For SRBrowserController
    if ([windowController isKindOfClass:[SRBrowserController class]]) {
        SRBrowserController*    browserController;
        browserController = (SRBrowserController*)windowController;
        
        // Get web view
        WebView*    webView;
        webView = [[browserController selectedPageController] webView];
        if (!webView) {
            return;
        }
        
        // Find string
        if ([webView searchFor:string direction:direction caseSensitive:NO wrap:YES]) {
            [_notFoundTextField setHidden:YES];
            if (flag) {
                [[self window] orderOut:self];
            }
        }
        else {
            [_notFoundTextField setHidden:NO];
            NSBeep();
        }
    }
#if 0
    // For SRSourceWindowController
    else if ([windowController isKindOfClass:[SRSourceWindowController class]]) {
        id textView=[(SRSourceWindowController*)windowController selectedTextView];
        if (!textView || ![textView respondsToSelector:@selector(searchFor:direction:caseSensitive:wrap:)]) {
            return;
        }
        
        // Find string
        if ([textView searchFor:string direction:direction caseSensitive:NO wrap:YES]) {
            [_notFoundTextField setHidden:YES];
            if (flag) {
                [[self window] orderOut:self];
            }
        }
        else {
            [_notFoundTextField setHidden:NO];
            NSBeep();
        }
    }
#endif
}

- (void)findNextAction:(id)sender
{
    [self findOnDirection:YES closeWindow:NO];
}

- (void)findNextAndCloseAction:(id)sender
{
    [self findOnDirection:YES closeWindow:YES];
}

- (void)findPreviousAction:(id)sender
{
    [self findOnDirection:NO closeWindow:NO];
}

- (void)useSelectionForFindAction:(id)sender
{
    // Get main window controller
    NSWindowController* windowController;
    windowController = [[NSApp mainWindow] windowController];
    if (!windowController) {
        return;
    }
    
    // For SRBrowserController
    if ([windowController isKindOfClass:[SRBrowserController class]]) {
        SRBrowserController*    browserController;
        browserController = (SRBrowserController*)windowController;
        
        // Get web view
        WebView*    webView;
        webView = [[browserController selectedPageController] webView];
        if (!webView) {
            return;
        }
        
        // Get selected string
        NSString*   selectedString;
        selectedString = [webView selectedString];
        if (selectedString) {
            [self setStringValue:selectedString];
        }
        
        return;
    }
#if 0
    // For SRSourceWindowController
    if ([windowController isKindOfClass:[SRSourceWindowController class]]) {
        id textView=[(SRSourceWindowController*)windowController selectedTextView];
        if (!textView || ![textView respondsToSelector:@selector(searchFor:direction:caseSensitive:wrap:)]) {
            return;
        }
        
        // Get selected string
        NSRange range;
        range = [textView selectedRange];
        if (range.length == 0) {
            return;
        }
        
        NSString*   selectedString;
        selectedString = [[[textView textStorage] string] substringWithRange:range];
        if (selectedString) {
            [self setStringValue:selectedString];
        }
        
        return;
    }
#endif
}

//--------------------------------------------------------------//
#pragma mark -- Menu item validation --
//--------------------------------------------------------------//

- (BOOL)validateMenuItem:(id<NSMenuItem>)menuItem
{
    // Get tag
    int tag;
    tag = [menuItem tag];
    
    switch (tag) {
    case SRCloseWindowTag: {
        [menuItem setKeyEquivalent:@"w"];
        [menuItem setKeyEquivalentModifierMask:NSCommandKeyMask];
        return YES;
    }
    case SRCloseTabTag: {
        [menuItem setKeyEquivalent:@""];
        return YES;
    }
    }
    
    return YES;
}

//--------------------------------------------------------------//
#pragma mark -- NSWindow delegate --
//--------------------------------------------------------------//

- (void)windowDidBecomeKey:(NSNotification*)notification
{
    // Update file menu
    [SRFileMenu() update];
}

@end
